Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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


In reply to When is $_ local and when is it not? by iakobski

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-20 08:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found