Perl foreach循环变量作用域 [英] Perl foreach loop variable scope

查看:193
本文介绍了Perl foreach循环变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是perl的新手,在编写以下代码段后,我对perl作用域规则感到困惑:

I am new to perl and was confused with perl scoping rules after I wrote below code snippet:

#!/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的值在循环退出后不会更改.这是怎么回事?

So the variable $i value is not changing after the loop exits. Whats going on in here?

推荐答案

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

According to the perldoc information regarding foreach loops: here

foreach循环遍历普通列表值并设置 变量VAR依次成为列表的每个元素.如果变量 以关键字my开头,然后在词法范围内,并且是 因此仅在循环内可见.否则,变量为 隐式地位于循环的本地,并在退出时恢复其以前的值 循环.如果该变量先前是用my声明的,则使用 该变量而不是全局变量,但仍本地化为 循环.这种隐式本地化仅发生在foreach循环中.

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的特殊变量$ _例如以下示例:

If you want to retain the value of $i outside the loop then you can omit $i in the foreach loop call and use perl's special variable $_ an example below:

#!/usr/bin/perl

use strict;
use warnings;

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

5 6 7 8 9 10 外循环i = 10

5 6 7 8 9 10 Outside loop i = 10

这篇关于Perl foreach循环变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆