IraTarball has asked for the wisdom of the Perl Monks concerning the following question:
I was just sitting there, writing some Perl, when I was slapped by confussion. I have this array, I'll call it
which I want to build into a linked list sort of structure. For the sake of a simple posting I'll make it more of a linked shrub like this.my @array = ();
So that all of the links just point to the '1' element of my array. This seems to work the way I wanted. If I print it out with this code$array[1] = { val => "The initial value for 1", one => 'undef' }; $array[0] = { val => "The initial value for 0", one => \$array[1]{val} + }; $array[2] = { val => "The initial value for 2", one => \$array[1]{val} + }; $array[3] = { val => "The initial value for 3", one => \$array[1]{val} + };
I getfor my $i (0 .. 3) { print "# $array[$i]{one}\n"; if (ref $array[$i]{one} eq 'SCALAR') { print "#\t${$array[$i]{one}}\n"; } }
So all the references have the same address and value. Great.# SCALAR(0x8114938) # The initial value for 1 # undef # SCALAR(0x8114938) # The initial value for 1 # SCALAR(0x8114938) # The initial value for 1
D'oh! Now things seem to be broken. The same section of code for printingfor my $i (0 .. 3) { $array[$i] = { val => rand(time)%3, one => \$array[1]{val} }; }
gives me the irritating output ofprint "\n"; for my $i (0 .. 3) { print "# $array[$i]{one}\n"; if (ref $array[$i]{one} eq 'SCALAR') { print "# \t${$array[$i]{one}}\n"; } }
Notice that the references have changed after reseting the value for @array[ 1 ]. So now $array[ 0 ]{one} points to the old value and the last 2 elements of the array point to the new value. The whole idea here was to have a reference to the value of $array[ 1 ]{val} so that other nodes would always have the current value, but that's broken.# SCALAR(0x8114938) # The initial value for 1 # SCALAR(0x8114938) # The initial value for 1 # SCALAR(0x81adcd8) # 0 # SCALAR(0x81adcd8) # 0
What is happening here?
I suspect that this has to do with scoping inside the loop's block and that I'm creating something like a closure. Can anyone confirm or deny this?
I don't have any great project hanging on this, in fact I have a working version thanks to merlyn's node on using push for this, but it's bugging me that I don't understand why this doesn't work.
Thanks for your time,
Peter C.,
"It's not the fact that I have the monkeys that gives me the power, it's that I'll turn the monkeys loose that gives me the power."
~Kids in the Hall
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Scope when initializing with references in a loop
by IraTarball (Monk) on Dec 06, 2001 at 04:08 UTC | |
|
Re: Scope when initializing with references in a loop
by George_Sherston (Vicar) on Dec 06, 2001 at 03:37 UTC | |
by IraTarball (Monk) on Dec 06, 2001 at 03:57 UTC |