这当然是在Perl文档中记录的 – 但是我没有记住或读取它.
以下脚本演示了我的意思:
use warnings; use strict; my $g = 99; foreach $g (1..5) { p($g); } sub p { my $l = shift; printf ("%2d %2d\n",$g,$l); }
脚本打印
99 1 99 2 99 3 99 4 99 5
因为$g被“本地化”到foreach循环.
据我所知,如果我在foreach循环中添加了$g:
foreach my $g (1..5) {
实际上,我最终做到这一点,因为我觉得它使得变量在循环中是局部的.
我现在的问题是:有没有一个我使用我的功能会发生变化的情况(假设$g已经在全球宣布).
解决方法
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 keywordmy
,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.
所有这一切从Private Variables via my()
from perlsub的这个片段进一步澄清
The
foreach
loop defaults to scoping its index variable dynamically in the manner oflocal
. However,if the index variable is prefixed with the keywordmy
,or if there is already a lexical by that name in scope,then a new lexical is created instead.
由于在这两种情况下都创建了一个新的词汇,所以不会有任何实际的区别.
我绝对支持并建议把我放在那里.