Perl中foreach循环的默认范围是多少?

前端之家收集整理的这篇文章主要介绍了Perl中foreach循环的默认范围是多少?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Perl中,在foreach循环中使用’my’有什么作用吗?似乎索引变量始终是本地的,不管是否使用’my’.那么你可以在foreach循环中放置’我的’,并且在循环体内仍然有私有的范围?

可以看出,使用’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'.

解决方法

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.

原文链接:https://www.f2er.com/Perl/172711.html

猜你在找的Perl相关文章