Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Dear Monks, when I first learned perl I read that one needs to be careful to avoid creating $_ in nested loops because the inner one will clobber the outer one. But on a whim I just created a program called x which contains the following and found that it WORKS!

for (<>) { print "Current line is $_"; for (split) { print "Current token is $_\n"; } }

When I type cat file | x, each line from file is first displayed and then each token within that line is displayed immediately afterwards. I would have thought that the outer "for" would create a list of values that are popped off and assigned to $_ one at time for each pass of the outer "for" loop, but that the inner "for" would replace that list with a list of its own. But that is not happening, the outer "for" is working fine as though the inner "for" was not there. It looks as if each execution of the inner "for" creates and then exhausts its own list whose values it assigns to its own $_ and that this has no effect on the list and the $_ that the outer "for" uses. I could understand this if there were a local $_ within the first pair of braces, but that's not the case here.

Before I start relying on this behavior in production programs that I write I wanted to seek your wisdom in confirming that this is expected perl behavior that I can reliably count on. Thank you!


In reply to Default variable $_ is not getting overwritten by fireblood

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 studying the Monastery: (5)
As of 2024-04-25 14:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found