Pathologically Eclectic Rubbish Lister | |
PerlMonks |
When is $_ local and when is it not?by iakobski (Pilgrim) |
on Jul 13, 2001 at 16:52 UTC ( [id://96369]=perlquestion: print w/replies, xml ) | Need Help?? |
iakobski has asked for the wisdom of the Perl Monks concerning the following question:
Now I usually only use $_ in very small
blocks of code, such as in a map or grep block. If the section of code large or is likely to grow then it is much clearer to assign to a named variable and this helps to document the code.
Today I was extending a bit of code that uses $_ absolutely everywhere and there was a point where the behaviour was a bit difficult to understand. I have always thought that you could assume that the magic of $_ made it work so that you could use it as if it were lexically scoped. So when you run this: the fact that there is a call to foo() should make no difference to the value printed. And as expected, it doesn't:
So what's the problem? Well if you change foo() to read: ie use while instead of for, then the output is: Now I found this quite surprising. So my questions are:
-- iakobski
Back to
Seekers of Perl Wisdom
|
|