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

Re^2: why need my in a foreach loop?

by 7stud (Deacon)
on Nov 28, 2010 at 19:59 UTC ( #874133=note: print w/ replies, xml ) Need Help??


in reply to Re: why need my in a foreach loop?
in thread why need my in a foreach loop?

Here's the difference:

use strict; use warnings; use 5.010; our $foo = 'hello'; sub f { print("$foo\n"); } for my $foo (qw( a b c )) { f(); } --output:-- hello hello hello

In ikegami's example, the my is omitted in the for loop, which causes the for loop to change the global variable $foo--and the subroutine prints the global $foo (i.e. the subroutine is a closure).


Comment on Re^2: why need my in a foreach loop?
Download Code
Replies are listed 'Best First'.
Re^3: why need my in a foreach loop?
by ikegami (Pope) on Nov 28, 2010 at 23:23 UTC

    the subroutine is a closure

    Backwards. It works because the subroutine doesn't capture package variables. If you switched our for my in my snippet, you'd have a closure, and you'd get a different result.

      Nice catch.

      If you switched our for my in my snippet, you'd have a closure, and you'd get a different result.

      Is that correct? Because the my variable would still be in scope, would the subroutine qualify as a closure? It's my understanding that a subroutine is a closure when it preserves a variable that has gone out of scope.

        I don't know the precise definition if there is one. For practical purposes, I find it doesn't matter.

        Correction: In this case, the sub truly acts as a closure. If it didn't, it wouldn't matter if you used our or my.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (17)
As of 2015-07-30 15:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (272 votes), past polls