⭐ 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 |
In Section
Seekers of Perl Wisdom