Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: why need my in a foreach loop?

by ikegami (Pope)
on Nov 28, 2010 at 04:55 UTC ( #874065=note: print w/ replies, xml ) Need Help??


in reply to why need my in a foreach loop?

When using strict perl requires to declare even the loop variable of a foreach loop.

It can use package variables, for starters.

our $foo; sub f { print("$foo\n"); } for $foo (qw( a b c )) { f(); # Prints a, b and c. }

Foreach loops existed long before "my".

Why is this code not allowed?

It generates an error for all instances of $word since you never declared it and you asked to make such things errors.


Comment on Re: why need my in a foreach loop?
Download Code
Re^2: why need my in a foreach loop?
by 7stud (Deacon) on Nov 28, 2010 at 19:59 UTC

    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).

      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.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (15)
As of 2014-07-10 22:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (217 votes), past polls