加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl foreach循环变量范围

发布时间:2020-12-15 23:22:33 所属栏目:大数据 来源:网络整理
导读:在我编写下面的代码片段后,我是perl的新手并且与perl范围规则混淆: #!/usr/bin/perlmy $i = 0;foreach $i(5..10){ print $i."n";}print "Outside loop i = $in"; 我期望输出如下: 5678910Outside loop i = 10 但它的给予: 5678910Outside loop i = 0 因
在我编写下面的代码片段后,我是perl的新手并且与perl范围规则混淆:

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

我期望输出如下:

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 = $in";

五678910外环i = 10

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读