perl - 为什么 Perl 的 foreach 不要求用 my 声明它的变量?

标签 perl variables foreach local-variables

今天,我在 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环形。

据我所知,如果我添加了 my 没有区别至 $g在 foreach 循环中:
foreach my $g (1..5) {

实际上,我最终这样做是因为我觉得它更清楚地表明变量是循环的局部变量。

我现在的问题是:是否有我使用 my 的场景?确实有所作为(鉴于 $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.



因此,使用 my 对其进行本地化应该没有区别。或将其留给 foreach .

有点好奇的是

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.



由于在这两种情况下都在内部创建了新的词法,因此没有任何实际区别。

我绝对支持并推荐(总是)拥有一个 my那里。

关于perl - 为什么 Perl 的 foreach 不要求用 my 声明它的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42243470/

相关文章:

perl - "IO::Socket::SSL 1.94+ required for TLS support"在 Heroku 上运行 Mojolicious 应用程序时出错

perl - 如何使用 mod_perl 发送自定义 http 状态代码

bash - Bash 中的动态变量名称

laravel - laravel 帖子的 index.php 中 undefined variable

c# - 无法使用 var 和 foreach 将 void 分配给隐式类型的局部变量

regex - 正则表达式在某个字符 R Perl 之前抓取单词

xml - 在 Perl 中使用 libxml 迭代元素

在 R 中使用 foreach 读取全局变量

java - 如何在 bash 变量中存储受计数影响的 PostgreSQL 插入查询行

r - R中的嵌套foreach循环以更新公共(public)数组