in reply to How do closures and variable scope (my,our,local) interact in perl?

The "our" case makes sense to me if the for loop is localizing the variable inside the loop. Thus when you call the subs outside the loop $name is undefined until you set it to something different (outside the loop). Here is the output if you comment out the second set of tests:

----- $name is constant inside sub ------ Use of uninitialized value $name in concatenation (.) or string at /tm +p/test.pl line 17. red: <FONT COLOR=''></FONT> Use of uninitialized value $name in concatenation (.) or string at /tm +p/test.pl line 17. violet: <FONT COLOR=''></FONT> ----- sub used inside loop that defined it ------ trying out red: <FONT COLOR='red'></FONT> trying out blue: <FONT COLOR='blue'></FONT> trying out green: <FONT COLOR='green'></FONT> trying out yellow: <FONT COLOR='yellow'></FONT> trying out orange: <FONT COLOR='orange'></FONT> trying out purple: <FONT COLOR='purple'></FONT> trying out violet: <FONT COLOR='violet'></FONT> ----- sub used outside of loop that assigned it ------ Use of uninitialized value $name in concatenation (.) or string at /tm +p/test.pl line 52. red: <FONT COLOR=''></FONT> green: <FONT COLOR='something wacky and wonderful'></FONT> violet: <FONT COLOR='something wacky and wonderful'></FONT>

I'm not so sure what is happening in the my case.

Good Day,
    Dean

Replies are listed 'Best First'.
Re^2: How do closures and variable scope (my,our,local) interact in perl?
by ELISHEVA (Prior) on Jun 16, 2009 at 12:19 UTC
    Thanks. In a private message Corion pointed me to perlsyn which has this to say about foreach loops and localization:
    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.

    As you have observed, apparently even without the use of my, the variable used for iteration in a foreach loop is implicitly localized. That is why it has a value inside the loop but not outside of it.

    However, this is supposed to happen for both my and our variables and it appears to be happening for only for the our variables. Hmmm.

    Best, beth