Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: for loop localisation bug?

by cees (Curate)
on Dec 29, 2003 at 15:06 UTC ( [id://317448]=note: print w/replies, xml ) Need Help??


in reply to for loop localisation bug?

This is actually the documented behaviour. Check out the perlsyn docs and you will see the followng:

The "foreach" loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword "my", then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with "my", it uses that variable instead of the global one, but it's still localized to the loop. This implicit localisation occurs only in a "foreach" loop.

- Cees

Replies are listed 'Best First'.
Re: Re: for loop localisation bug?
by BrowserUk (Patriarch) on Dec 29, 2003 at 15:21 UTC

    Thanks cees. That's what I was missing. I'm amazed I never encountered this before, but I guess it just shows how infrequently you need to know at what point a for loop exits.

    It's no problem to re-code this as a c-style for, or any number of other ways, but it did surprise me.

    perl -le" my $n; for( $n=0; $n <=10; $n++ ){ print $n; last if $n == 5 + }; print '$n= ', $n;" 0 1 2 3 4 5 $n= 5

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    Hooray!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-03-28 17:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found