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.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...