在Perl中,在foreach循环中使用'my'会产生什么影响吗?无论是否使用'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 …为什么$i在以下代码中没有重新声明的警告?
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
for my $i (1..3) {
  my $i = 'DUMMY';
  print Dumper $i;
}
use warnings;
use strict;
my $count = 4;
for $count (1..8) {
    print "Count = $count\n";
    last if ($count == 6);
}
if (not defined($count)) {
    print "Count not defined\n";
}
else {
    print "Count = $count\n";
}
这打印:
1
2
3
4
5
6
4
为什么?因为for循环$count在其块内创建了自己的词法范围版本.
use warnings;
use strict;
my $count;
for $count (1..8) {
    print "Count = $count\n";
    last if ($count == 6);
}
if (not defined($count)) {
    print "Count not …