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

为什么Perl的foreach要求它的变量被声明为我的?

发布时间:2020-12-15 21:26:57 所属栏目:大数据 来源:网络整理
导读:今天,我偶然发现Perl中的某些东西,我没有意识到:它将本地化??列表的元素分配给变量. 这当然是在Perl文档中记录的 – 但是我没有记住或读取它. 以下脚本演示了我的意思: use warnings;use strict;my $g = 99;foreach $g (1..5) { p($g);}sub p { my $l = sh
今天,我偶然发现Perl中的某些东西,我没有意识到:它将本地化??列表的元素分配给变量.

这当然是在Perl文档中记录的 – 但是我没有记住或读取它.

以下脚本演示了我的意思:

use warnings;
use strict;

my $g = 99;

foreach $g (1..5) {
  p($g);
}

sub p {
  my $l = shift;
  printf ("%2d %2dn",$g,$l);
}

脚本打印

99  1
99  2
99  3
99  4
99  5

因为$g被“本地化”到foreach循环.

据我所知,如果我在foreach循环中添加了$g:

foreach my $g (1..5) {

实际上,我最终做到这一点,因为我觉得它使得变量在循环中是局部的.

我现在的问题是:有没有一个我使用我的功能会发生变化的情况(假设$g已经在全球宣布).

解决方法

被调查的行为记录在 Foreach Loops in perlsyn年

The foreach loop iterates over a normal list value and sets the scalar 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.

所有这一切从Private Variables via my() from perlsub的这个片段进一步澄清

The foreach loop defaults to scoping its index variable dynamically in the manner of local. However,if the index variable is prefixed with the keyword my,or if there is already a lexical by that name in scope,then a new lexical is created instead.

由于在这两种情况下都创建了一个新的词汇,所以不会有任何实际的区别.

我绝对支持并建议把我放在那里.

(编辑:李大同)

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

    推荐文章
      热点阅读