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":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.