Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^2: Hidden Secrets of PERL

by Hue-Bond (Priest)
on Oct 11, 2006 at 22:58 UTC ( [id://577729]=note: print w/replies, xml ) Need Help??


in reply to Re: Hidden Secrets of PERL
in thread Hidden Secrets of PERL

If the variable that is going to hold each value in an loop already exists as a lexical one (first example), foreach creates a new lexical whose scope is the loop block. If it exists as a package global (second example), foreach localizes it, thus making its scope dynamic. That's why second example's print_foo sees the dynamic content.

--
David Serrano

Replies are listed 'Best First'.
Re^3: Hidden Secrets of PERL
by bart (Canon) on Oct 12, 2006 at 11:08 UTC
    Indeed and this is documented in perlsyn under the heading "foreach loops":
    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.

    OTOH, it doesn't seem to be really localized, instead, it appears to be a totally different lexical.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-19 15:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found