Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^4: foreach-loop-local var in sub

by Athanasius (Chancellor)
on Jan 22, 2013 at 03:54 UTC ( #1014557=note: print w/replies, xml ) Need Help??


in reply to Re^3: foreach-loop-local var in sub
in thread foreach-loop-local var in sub

Well, Foreach Loops’s use of the word “local” is somewhat misleading, as it suggests dynamic scoping (via the local keyword), whereas the scoping here is lexical. The Camel Book (4th Edition, page 143, underlining added) is a little clearer:

The loop variable is valid only from within the dynamic or lexical scope of the loop and will be implicitly lexical if the variable was previously declared with my. This renders it invisible to any function defined outside the lexical scope of the variable, even if called from within that loop. However, if no lexical declaration is in scope, the loop variable will be a localized (dynamically scoped) global variable; this allows functions called from within the loop to access that variable. In either case, any previous value the localized variable had before the loop will be restored automatically upon loop exit.

The dynamic scoping of a global variable can be easily seen by changing my $i = 6; to our $i = 6; in NetWallah’s example.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^5: foreach-loop-local var in sub
by LanX (Bishop) on Jan 22, 2013 at 04:00 UTC
    I know, we had this discussion quite often in the past.

    But IMHO we should steal the explanation from the Camel-Book and put it into the POD.

    Cheers Rolf

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1014557]
help
Chatterbox?
[holli]: I got into a fight yesterday and won.
[holli]: No, that's not true. I started it.
[holli]: I was company to my mother, bringing her to the therapy she has to take. There was another so called therapist outside smoking. We engaged in a talk with her and he turned out to be one of these lunatics telling people when they are sick it's their own
[holli]: fault for not thinking positively enough.
[LanX]: did he seriously hurt his fist at your nose in the end?

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2017-12-13 17:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What programming language do you hate the most?




















    Results (373 votes). Check out past polls.

    Notices?