Perl中foreach循环的默认范围是什么? [英] What is the default scope of foreach loop in Perl?
问题描述
可以看出,使用'for'循环使用/不使用'my'是有区别的:
use strict;
使用警告;
$ b $ my($ x,$ y)=('INIT','INIT');
my $ temp = 0; ($ x = 1; $ x< 10; $ x ++){
$ temp = $ x + 1;
;
}
printThis is x:$ x \\\
; #打印这是x:10'。 (my $ y = 1; $ y <10; $ y ++){
$ temp = $ y + 1;
;
}
print这是y:$ y \\\
; #打印这是y:INIT。
但在foreach上看起来没有效果:
my($ i,$ j)=('INIT','INIT');
foreach $ i(1..10){
$ temp = $ i + 1;
}
print\\\
This is i:$ i\\\
; #打印这是我:初始化。
foreach my $ j(1..10){
$ temp = $ j + 1;
}
print\\\
This is j:$ j\\\
; #打印这是j:INIT。
From http://perldoc.perl.org/perlsyn.html#Foreach-Loops :
foreach循环遍历一个正常的列表值,并将变量VAR设置为列表中的每个元素。如果变量前面带有关键字my,那么它是词法范围的,因此只在循环中可见。否则,该变量对于循环隐式地是局部的并且在退出循环时重新获得其以前的值。如果变量先前是用my声明的,那么它使用该变量而不是全局变量,但是它仍然是本地化的。这种隐式的本地化只发生在一个foreach循环中。
In Perl, does using 'my' within a foreach loop have any effect? It seems that the index variable is always local whether or not 'my' is used. So can you drop the 'my' within the foreach loop and still have private scope within the body of the loop?
As can be seen, using the 'for' loop there is a difference between using / not using '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'.
But on foreach it does not seem to have an effect:
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'.
From http://perldoc.perl.org/perlsyn.html#Foreach-Loops:
The foreach loop iterates over a normal list value and sets the 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 localisation occurs only in a foreach loop.
这篇关于Perl中foreach循环的默认范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!