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:
- Is it supposed to do this?
- Is this behaviour documented?
- Why is there a big difference between for and while?
--
iakobski
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.