professa has asked for the wisdom of the Perl Monks concerning the following question:
Is it possible to "share" a variable in subroutines? I have a subroutine, in which I declare an array.
This array should be only "visible" inside this subroutine *and* all other subroutines which are called from inside that specific subroutine:
sub callme ($) { my $i = $_[0]; $array[$i] = "printme-"; } sub specific { my @array = [0, 1, 2, 3, 4, 5]; for (my $i=0; $i<6; $i++) { &callme($i); } print @array; }
The print-statement should print:
printme-printme-printme-printme-printme-printme-.
Is this possible? Putting sub callme() inside of sub specific() gives a warning stating to use an anonymous subroutine, but how do I call it from within sub specific() if it's anonymous?
I want to avoid copying around eventually quite large segments of memory when referencing and derefencing that array when passing as \@array to the called subroutine.
btw: the called subroutine does more to the array-element than just setting a new value, so it's recommended to use a subroutine here and not to put the code inside sub specific(). ;-)
Thanx in advance!
Micha
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Sharing a variable between subroutines
by clintp (Curate) on Dec 28, 2001 at 21:17 UTC | |
|
(jeffa) Re: Sharing a variable between subroutines
by jeffa (Bishop) on Dec 28, 2001 at 21:29 UTC | |
by Anonymous Monk on Dec 28, 2001 at 21:47 UTC | |
|
(Ovid) Re: Sharing a variable between subroutines
by Ovid (Cardinal) on Dec 28, 2001 at 21:35 UTC | |
by tilly (Archbishop) on Jan 05, 2002 at 19:37 UTC | |
|
Re: Sharing a variable between subroutines
by davorg (Chancellor) on Dec 28, 2001 at 21:18 UTC | |
|
Re: Sharing a variable between subroutines
by rbc (Curate) on Dec 28, 2001 at 23:00 UTC |