>>>>> "BF" == Brian Fraser <frase...@gmail.com> writes:
BF> On Fri, Jun 3, 2011 at 1:23 PM, Jim Gibson <jimsgib...@gmail.com> wrote: >> Declare the variable just before the loop, and remove the 'my' from the >> foreach statement: >> >> my $name; >> foreach $name ( ... ) { >> ... >> } >> BF> That won't do. What that code actually translated to is BF> my $name; BF> for my $name ( ... ) { ... } not true. perl -le 'my $x = "zzz" ; for $x ( qw( foo bar ) ) { print "L: $x" } print "E: $x"' L: foo L: bar E: zzz foreach without a my will localize the loop variable. that isn't the same as my. BF> With the second $name masking the first! IIRC this is explained BF> somewhere in PBP, but I don't have the book at hand right now. In BF> any case, if you want to use the variable outside of the for, BF> don't name the two variables the same. The rough rule of thumb is BF> that leaving off the my in a for(each) is probably introducing BF> subtle bugs into your program. why search PBP when the perldocs are very clear about it and easily searched? from perldoc perlsyn: The "foreach" loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword "my", then it is lexically scoped, and is therefore visible only within the loop. 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. This implicit localisation occurs only in a "foreach" loop. so in my oneliner the my allowed the $x to not need redeclaring in the foreach but it still localized the value to the loop. but as i said in another post, the OP just likely wants to use $name as a loop var again which he can with another my declare. uri -- Uri Guttman ------ u...@stemsystems.com -------- http://www.sysarch.com -- ----- Perl Code Review , Architecture, Development, Training, Support ------ --------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com --------- -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/