nop has asked for the wisdom of the Perl Monks concerning the following question:

use strict; my ($x, $y); foreach $x (1..10) { print "in loop x=$x\n"; last if ($x >= 5); } print "after loop x=$x\n"; foreach my $y (1..10) { print "in loop y=$y\n"; last if ($y >= 5); } print "after loop y=$y\n";
I would have thought that these two loops would behave differently...

I expected the first block to print after loop x=5 and the second to print after loop y=...

Why doesn't the first block modify $x?

nop

Replies are listed 'Best First'.
Re: Scoping question
by chipmunk (Parson) on Dec 07, 2000 at 20:19 UTC
    Let's look into perlsyn to figure this one out... Ah, here it is:
    Foreach Loops 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.
    So, the loop variable is always local to the loop, whether it's a lexical or a package variable.