Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
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.

Replies are listed 'Best First'.
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?
[tye]: disable /proc and then see what it does?
[davido]: then it reads from /etc/passwd to decide who my uid is.
[davido]: sorry, typed that before you asked me to disable proc
[davido]: but you stumped me; don't know how to disable proc.
[tye]: I don't know if you can just dismount, but I thought so.
[davido]: yeah, umount -f isn't powerful enough.
[tye]: probably something in the init subsystem that does the mounting that you could disable and reboot.
davido needs to close laptop to board flight home from yapc.
[davido]: I'll look into it in a few hours probably.
[davido]: when i do get to that point I think I'll do it in a vm snapshot just in case. :)

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2017-06-23 20:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many monitors do you use while coding?















    Results (555 votes). Check out past polls.