Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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

by ajdelore (Pilgrim)
on Jul 21, 2003 at 23:51 UTC ( #276542=note: print w/replies, xml ) Need Help??

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); }


Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://276542]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2021-09-23 21:25 GMT
Find Nodes?
    Voting Booth?

    No recent polls found