in reply to Why is it uninitialized?

From the documentation on the foreach loop (https://perldoc.perl.org/perlsyn.html#Foreach-Loops):
The foreach loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list in turn. 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 localization occurs only in a foreach loop.

The foreach keyword is actually a synonym for the for keyword, so you can use either. If VAR is omitted, $_ is set to each value.

Update: added some formatting in the above quote.

Replies are listed 'Best First'.
Re^2: Why is it uninitialized?
by Eily (Monsignor) on Dec 20, 2017 at 21:17 UTC

    Except the effect of local also applies to the called subroutines,as shown by the our version. perlsub says:

    A local modifies its listed variables to be "local" to the enclosing block, eval, or do FILE --and to any subroutine called from within that block. A local just gives temporary values to global (meaning package)
    So while local is supposed to work across calls to subroutines, it's also supposed to work on variables which are present in the symbols table. I wouldn't expect a closure to keep the name of the variable, or whatever is used to make the localization work

      Yeah, Eily, I understand your point.

      I am not quite sure, though, whether the sentence the variable is implicitly local to the loop and regains its former value upon exiting the loop is to be construed as meaning that it works as if the loop variable is localized with the local keyword.

        Yes you're right, as confirmed here.

Re^2: Why is it uninitialized?
by poj (Abbot) on Dec 20, 2017 at 19:48 UTC
    Presumably the declaration with our prevents the implicit localization within the loop.

    poj