http://qs321.pair.com?node_id=276541

ajdelore has asked for the wisdom of the Perl Monks concerning the following question: (input and output)

How do I localize $_ in while loops?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I localize $_ in while loops?
by ajdelore (Pilgrim) on Jul 21, 2003 at 23:51 UTC

    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.

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

      This doesn't work, because $_ is never assigned to. I think you took it from this example code:

      { local $_; while(<>){ print; } }

      This works because the assignment to $_ is taken care of by using angle brackets alone inside the while. I think you meant:

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

      --
      3dan
Re: How do I localize $_ in while loops?
by Roy Johnson (Monsignor) on Nov 03, 2003 at 22:30 UTC
    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.