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.