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

前端之家收集整理的这篇文章主要介绍了为什么Perl的foreach要求它的变量被声明为我的?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
今天,我偶然发现Perl中的某些东西,我没有意识到:它将本地化​​列表的元素分配给变量.

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

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

use warnings;
use strict;

my $g = 99;

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

sub p {
  my $l = shift;
  printf ("%2d %2d\n",$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.

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

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

猜你在找的Perl相关文章