(s)coping with foreachby greenFox (Vicar)
|on Apr 01, 2001 at 07:14 UTC||Need Help??|
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-
expecting it to output
what it actually outputs is
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-
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-
following everything I had discovered so far I expected to get
++ to any-one who can guess what it actually prints because on my system (v5.6, rh7.0) it prints-
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 :)