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


in reply to How do I localize $_ in while loops?

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.

Replies are listed 'Best First'.
Re: Answer: How do I localize $_ in while loops?
by edan (Curate) on Jul 22, 2003 at 15:59 UTC
    { 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