为什么 Perl 的 foreach 不要求它的变量用 my 声明?
Why doesn't Perl's foreach require its variable to be declared with my?
今天,我在 Perl 中偶然发现了一些我不知道的东西:它 "localizes" 将迭代列表的元素分配给的变量。
这当然记录在 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
是 "localized" 到 foreach
循环。
据我所知,如果我在 foreach 循环中将 my
添加到 $g
没有区别:
foreach my $g (1..5) {
实际上,我最终这样做是因为我觉得它更清楚地表明变量是循环的局部变量。
我现在的问题是:是否存在我使用 my
确实有所作为的情况(假定 $g
已在全球范围内声明)。
调查的行为记录在 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.
继续解释
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.
因此,使用 my
本地化或将其留给 foreach
本地化应该没有区别。
有点好奇的是
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 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.
因为在这两种情况下都在内部创建了一个新的词法,因此没有任何实际差异。
我绝对支持并推荐(总是)在那里有一个my
。
今天,我在 Perl 中偶然发现了一些我不知道的东西:它 "localizes" 将迭代列表的元素分配给的变量。
这当然记录在 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
是 "localized" 到 foreach
循环。
据我所知,如果我在 foreach 循环中将 my
添加到 $g
没有区别:
foreach my $g (1..5) {
实际上,我最终这样做是因为我觉得它更清楚地表明变量是循环的局部变量。
我现在的问题是:是否存在我使用 my
确实有所作为的情况(假定 $g
已在全球范围内声明)。
调查的行为记录在 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 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.
因此,使用 my
本地化或将其留给 foreach
本地化应该没有区别。
有点好奇的是
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.
因为在这两种情况下都在内部创建了一个新的词法,因此没有任何实际差异。
我绝对支持并推荐(总是)在那里有一个my
。