Perl foreach循环变量范围

前端之家收集整理的这篇文章主要介绍了Perl foreach循环变量范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我编写下面的代码片段后,我是perl的新手并且与perl范围规则混淆:

#!/usr/bin/perl
my $i = 0;
foreach $i(5..10){
    print $i."\n";
}
print "Outside loop i = $i\n";

我期望输出如下:

5
6
7
8
9
10
Outside loop i = 10

但它的给予:

5
6
7
8
9
10
Outside loop i = 0

因此,循环退出后变量$i值不会改变.这是怎么回事?

解决方法

根据有关foreach循环的perldoc信息: here

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 localization occurs only in a foreach loop.

如果你想在循环外保留$i的值,那么你可以在foreach循环调用中省略$i并使用perl的特殊变量$_,如下所示:

#!/usr/bin/perl

use strict;
use warnings;

my $i = 0;
foreach (5..10){
    print $_."\n";
    $i = $_;
}
print "Outside loop i = $i\n";

五678910外环i = 10

猜你在找的Perl相关文章