Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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

( #276542=categorized answer: print w/ replies, xml ) Need Help??

Q&A > input and output > 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.

Comment on Answer: How do I localize $_ in while loops?
Select or Download Code
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
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 rifling through the Monastery: (3)
As of 2014-07-31 00:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (241 votes), past polls