in reply to Re^2: foreach-loop-local var in sub
in thread foreach-loop-local var in sub
Otherwise, the variable is
implicitly local to the loop and regains its former value upon exiting
the loop. If the variable was previously declared with "my", it uses
that variable instead of the global one, but it’s still localized to
the loop.
If you also check the references you will see that the '$i' are pointing to different locations.
OUTPUTuse strict; use warnings; $,=","; $\="\n"; my $i = 6; sub my_print { print $i,\$i; } ; for $i (qw|x y|) { my_print(); print " (Perl Style:\$i==$i)",\$i,"\n"; }
6, SCALAR(0x8fa4e38) (Perl Style:$i==x), SCALAR(0x8f86760), 6, SCALAR(0x8fa4e38) (Perl Style:$i==y), SCALAR(0x8fa4da8),
That's why PBP says to always use lexical loop vars in foreach!
Cheers Rolf
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: foreach-loop-local var in sub
by Athanasius (Archbishop) on Jan 22, 2013 at 03:54 UTC | |
by LanX (Saint) on Jan 22, 2013 at 04:00 UTC |