iakobski has asked for the wisdom of the Perl Monks concerning the following question:
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:use strict; for (1..3){ print "BEFORE: " . $_; foo(); print " AFTER: " . $_ . "\n"; } sub foo{ for(<DATA>){ last; } } __DATA__ a b c
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:
ie use while instead of for, then the output is:sub foo{ while(<DATA>){ last; } }
Now I found this quite surprising. So my questions are:BEFORE: 1 AFTER: a BEFORE: 2 AFTER: b BEFORE: 3 AFTER: c ========== [C:\users\jake\code\komodo\test2.pl] run finished. ======== +==
-- iakobski
|
---|