【发布时间】:2010-02-10 16:43:53
【问题描述】:
在 Perl 中,在 foreach 循环中使用 'my' 有什么效果吗?无论是否使用“我的”,索引变量似乎总是本地的。那么你可以在 foreach 循环中删除'my'并且在循环体中仍然拥有私有作用域吗?
可以看出,使用'for'循环有使用/不使用'my'的区别:
use strict;
use warnings;
my ($x, $y) = ('INIT', 'INIT');
my $temp = 0;
for ($x = 1; $x < 10; $x++) {
$temp = $x+1;
}
print "This is x: $x\n"; # prints 'This is x: 10'.
for (my $y = 1; $y < 10; $y++) {
$temp = $y+1;
}
print "This is y: $y\n"; # prints 'This is y: INIT'.
但在foreach上似乎没有效果:
my ($i, $j) = ('INIT', 'INIT');
foreach $i (1..10){
$temp = $i+1;
}
print "\nThis is i: $i\n"; # prints 'This is i: INIT'.
foreach my $j (1..10){
$temp = $j+1;
}
print "\nThis is j: $j\n"; # prints 'This is j: INIT'.
【问题讨论】:
-
我们在Learning Perl 中介绍了这一点,它是foreach 循环文档的第一段。 :)
-
提示:当您在代码前面加上
use strict; use warnings;时会发生什么情况? -
@Ether -- 添加了 strict 以清理主要示例。重点仍然集中在 for 和 foreach 默认上下文之间的区别上。感谢大家的帮助,我现在明白 foreach 循环中的默认范围是明确的“本地”或动态范围,而不是词法“我的”范围或全局“包”范围。
-
我的意思是,当您拥有
use strict; use warnings;时,您根本不能省略my。 -
@Ether。我添加了使用警告;并且——只要声明了变量——看起来还可以(至少在我运行它时)。你不能不省略'my'并获得默认的'local'范围吗?