http://www.perlmonks.org?node_id=68776

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

I feel like I should add a disclaimer to this post, there could be some mistakes due to misunderstanding... please be gentle :) I was playing with some code, reduced here to-
use strict; my $var=0; for $var (1..9){ print $var; } print "\n", $var, "\n";

expecting it to output

        123456789
	9

what it actually outputs is

	
	123456789
	0

I got all excited thinking I had found a bug :) A quick search showed that it was in fact a "feature", the for loop localises the variable, Dominus describes it well here. Admittedly I know little of the wonders of perl internals but as a user of the language I agree with Dominus that "lexically scoping" (NB1) the index variable is a mistake, perl lets the programmer hang themselves in countless other ways without quibble and to get what I originally wanted I have to write-

my $var1=0; for my $var2 (1..9){ print $var2; $var1 = $var2; } print "\n", $var1, "\n";

or some other gymnastics?

am I right in thinking that it is this way so that you can write nested foreach loops without $_ clobbering itself all over the place? If that is the only reason why not check to see if the index variable is $_ and only localise then?

And just when I thought I had finally "got it" I tried this-

use strict; my $var; for ($var=1; $var < 10; ++$var){ print $var; } print "\n", $var, "\n";

following everything I had discovered so far I expected to get

        123456789
        0

++ to any-one who can guess what it actually prints because on my system (v5.6, rh7.0) it prints-

	123456789
	10

Not only is $var not localised by the for loop but it gets mysteriously incremented AFTER the loop has finished (at this point I did think that "duh! its because of when the ++ is happening" but combinations of $var++ and <= all behave the same), is *this* a feature as well?

NB1. As an aside I had to go look up lexical (Oxford paperback) because while I know what was meant from context I didn't know what it meant, lexical means "words of a language", in this case I interpreted it as the language is perl and the variable is scoped by the word "foreach". The camel (v2) defines lexical scoping as "variables whach are visible only from their point of declaration down to the end of the block in which they are declared", I should have looked in the camel first :)

--
my $chainsaw = 'Perl';