Why doesn't Perl's foreach require its variable to be declared with my?

前端 未结 1 518
醉酒成梦
醉酒成梦 2021-01-04 08:06

Today, I stumbled over something in Perl I was not aware of: it \"localizes\" the variable that the elements of the list iterated over is assigned to.

This, of cours

1条回答
  •  -上瘾入骨i
    2021-01-04 08:44

    The investigated behavior is documented in Foreach Loops in perlsyn

    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.

    which continues to the explanation

    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.

    Thus there should be no difference between localizing it with my or leaving that to foreach.

    A little curiosity is that

    This implicit localization occurs only in a foreach loop.

    All this is further clarified in this snippet from Private Variables via my() from perlsub

    The foreach loop defaults to scoping its index variable dynamically in the manner of local. However, if the index variable is prefixed with the keyword my, or if there is already a lexical by that name in scope, then a new lexical is created instead.

    Since a new lexical is created inside in both cases there cannot be any practical difference.

    I absolutely support and recommend (always) having a my there.

    0 讨论(0)
提交回复
热议问题