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!
  • 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, 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
  • 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.