http://qs1969.pair.com?node_id=96369

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:

use strict; for (1..3){ print "BEFORE: " . $_; foo(); print " AFTER: " . $_ . "\n"; } sub foo{ for(<DATA>){ last; } } __DATA__ a b c
the fact that there is a call to foo() should make no difference to the value printed. And as expected, it doesn't:
BEFORE: 1 AFTER: 1 BEFORE: 2 AFTER: 2 BEFORE: 3 AFTER: 3 ========== [C:\users\jake\code\komodo\test2.pl] run finished. ======== +==

So what's the problem? Well if you change foo() to read:

sub foo{ while(<DATA>){ last; } }
ie use while instead of for, then the output is:
BEFORE: 1 AFTER: a BEFORE: 2 AFTER: b BEFORE: 3 AFTER: c ========== [C:\users\jake\code\komodo\test2.pl] run finished. ======== +==
Now I found this quite surprising. So my questions are:

-- iakobski