看下面代码:
#!/usr/bin/perl -w
my $x = 1;
for $x (5 ... 8){
print "In the for loop, \$x=[$x]\n";
}
print "\nOut of for loop, \$x=[$x]\n";
[/perl]
输出结果如下:
[perl]
$ ./test.pl
In the for loop, $x=[5]
In the for loop, $x=[6]
In the for loop, $x=[7]
In the for loop, $x=[8]
Out of for loop, $x=[1]
即 $x 做为for循环的临时变量,当for循环退出时,$x的值被恢复。
这是Perl中for的特性,一定要牢记。
修改代码如下:
use Scalar::Util qw(refaddr);
use strict;
my $x = 1;
print "Bef the for loop, \$x=[$x], addr=" . refaddr(\$x) . "\n\n";
for $x (5 ... 8){
print "In the for loop, \$x=[$x], addr=" . refaddr(\$x) . "\n";
}
print "\nOut of for loop, \$x=[$x], addr=" . refaddr(\$x) . "\n";
输出结果如下:
$ ./test.pl
Bef the for loop, $x=[1], addr=6696768
In the for loop, $x=[5], addr=6537872
In the for loop, $x=[6], addr=6537872
In the for loop, $x=[7

本文介绍了Perl中foreach循环的工作原理,强调了循环变量$x在循环结束后会恢复到初始状态。此外,还讲解了如何使用foreach处理数组或列表,并指出在循环中对控制变量的修改会影响到列表本身。最后,文章提到了Perl的默认变量$_,在循环中可以省略控制变量,Perl会自动使用$_,并在其他场景下也经常被默认使用。
最低0.47元/天 解锁文章
2102

被折叠的 条评论
为什么被折叠?



