Do you know where your variables are? | |
PerlMonks |
Scope when initializing with references in a loopby IraTarball (Monk) |
on Dec 06, 2001 at 02:51 UTC ( [id://129783]=perlquestion: print w/replies, xml ) | Need Help?? |
IraTarball has asked for the wisdom of the Perl Monks concerning the following question:
Greetings bretheren and sisteren,
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. 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 I get So all the references have the same address and value. Great. But no one would initialize an array like this, so I do it in a loop D'oh! Now things seem to be broken. The same section of code for printing gives me the irritating output of 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. 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,
"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."
Back to
Seekers of Perl Wisdom
|
|