Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

How do I localize $_ in while loops?

( #276541=categorized question: print w/ replies, xml ) Need Help??
Contributed by ajdelore on Jul 21, 2003 at 23:49 UTC
Q&A  > input and output


Answer: How do I localize $_ in while loops?
contributed by ajdelore

As discussed here, $_ is automatically localized in a foreach loop. So, for example:

foreach (qw/foo bar/) { print; print foreach (qw/one two three/); } # output: fooonetwothreebaronetwothree

However, a while loop does not do this automatically:

foreach (qw/foo bar/) { print; my @list = qw/one two three/; print while (shift @list); } # output: foofoofoofoobarbarbarbar

In order to do this, you need to explicitly localize $_ within the while loop:

foreach (qw/foo bar/) { print; my @list = qw/one two three/; print while (local $_ = shift @list); } # output: fooonetwothreebaronetwothree

Another way to do it:

{ local $_; print while (shift @list); }

Note that you must have the local declaration enclosed in a block with the while statement, as above. The following example will not work:

# will not localize $_ to the while loop local $_; print while (shift @list);

See perlop for more information.

Answer: How do I localize $_ in while loops?
contributed by Roy Johnson

Please note that shift does not populate $_ by default, so ajdelore's "Another way to do it" is not. The assignment still has to be explicit.

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?
    Username:
    Password:

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

    How do I use this? | Other CB clients
    Other Users?
    Others scrutinizing the Monastery: (4)
    As of 2014-10-24 21:22 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      For retirement, I am banking on:










      Results (137 votes), past polls