perl - 在 Continue block 中使用 For 循环中声明的词法变量

标签 perl

我在让我的一个模块编译时遇到了问题,看起来像是变量范围问题,但我不明白为什么。

示例代码:

PATH: foreach my $path (@paths) {
    open(my $file, '<', $path) or next PATH;

    my %properties;
    LINE: while (<$file>) {
        $_ =~ /$property_regex/ or next LINE;
        $properties{$1} = $2;
    }

    foreach (@property_keys) {
        unless ($properties{$_}) {
            # do stuff
            next PATH;
    }

    if ( $irrelevant_condition ) {
        # do stuff
        next PATH;
    }

    foreach my $new_var (@new_list) {
        # do stuff (does not iterate PATH loop)
    }
} continue {
    if (defined $file) { close($file) or die; }
}

翻译成上面的精简代码,我得到的错误是:

Global symbol "$file" requires explicit package name at line 25

也就是说,它似乎在提示在底部的 continue block 中使用了 $file。如您所见,$file 在第 2 行被声明为一个词法变量,在外部 foreach 循环(标记为 PATH)中。

但是,基于 perldoc for continue ,我希望 $file 仍然在范围内:

[...] it is always executed just before the conditional is about to be evaluated again, just like the third part of a for loop in C. Thus it can be used to increment a loop variable, even when the loop has been continued [...]

为了能够增加循环变量,是否将 continue block 视为与其所附加的循环相同的词法范围的一部分?

我错过了什么?


注意:这个模块是一个 Moo 类,所以虽然我在任何地方都没有明确的 use strict 语句,但 when you use Moo we enable strict and warnings .

最佳答案

您的 $path 变量仍在 continue BLOCK 的范围内,但是 for 的 BLOCK 中的内容超出范围,因为你已经到达了那个 BLOCK 的末尾(你已经到达了结束括号/退出了括号)。但是,$path 变量不在大括号内,因此可以在 continue BLOCK 中看到(即使它在大括号之外不可见)。

如果语法是这样的:

for (...)
{
 $x = stuff();
 continue { more_stuff($x) }
}

那么我希望 $x 可见。 IIRC,perl 6 有这样的东西,但在 perl 5 中,continue BLOCK 在循环 block 之外,因此在该 block 内看不到词法变量。

关于perl - 在 Continue block 中使用 For 循环中声明的词法变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387484/

相关文章:

multithreading - perl:在不按 “enter”的情况下不会退出

perl - Perl 中 ~~ 的对面

perl - 在 Vim 中,如何避免将 "/*"视为注释

perl - 确定屏幕尺寸的跨平台技术

excel - 使用 perl 在同一工作表中的直方图

windows - 如何调用传递给被调用程序的 VAR=$VAL 的系统?

perl - 如何在 Perl 中使用 DBI 按顺序获取列名和行数据?

php - 获取远程文本文件、处理和更新数据库——要使用的方法和脚本语言?

linux - 检查 SSH 隧道是否已启动并正在运行

perl - 如何从 Unix 中的文件打印特定行?