perl 'last' 语句和变量范围

标签 perl loops break

应该是简单的 Perl 构造并没有像我预期的那样运行。

@closest 数组包含“NNN-NNN”形式的字符串。我试图找到初始“NNN”与特定值匹配的第一个数组元素。

由于我在循环外声明了 $compoundKey,我希望它是持久的。循环按预期运行,当我得到匹配时退出。但是,代码退出循环后,$compoundKey 变量为空。 (查看代码后的日志输出。我正在寻找“83”。匹配的元素不是数组中的最后一个元素。)

    my $compoundKey;
    foreach $compoundKey (@closest)
    {
        logentry("In loop compoundKey is $compoundKey\n");
        last if ($compoundKey =~ /^$RID/);   
    }
    logentry("Outside loop compoundKey is $compoundKey\n");

日志文件:

    2019-02-27 18:15:26: In loop compoundKey is 90-1287
    2019-02-27 18:15:26: In loop compoundKey is 86-1223
    2019-02-27 18:15:26: In loop compoundKey is 86-1235
    2019-02-27 18:15:26: In loop compoundKey is 87-1316
    2019-02-27 18:15:26: In loop compoundKey is 89-1219
    2019-02-27 18:15:26: In loop compoundKey is 83-1224
    2019-02-27 18:15:26: Outside loop compoundKey is 

我假设我可以通过将临时循环变量显式分配给 $compoundKey 来解决此问题,但我仍然有些迷惑。我的代码中是否有一些我没有看到的错误?还是 Perl 中的“last”语句的行为方式与 C 或 Java 中的“break”完全不同?

谢谢!

最佳答案

这不是 last 语句,it's the foreach statement .

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. (Emphasis added).

关于perl 'last' 语句和变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54898332/

相关文章:

PHP循环;如何打印每个结果并在回显另一个结果之前延迟一秒钟?

javascript - 从对象中获取元素并与数组进行比较 - Jquery

python - 通过 KeyboardInterrupt 停止 pyzmq 接收器

python - 当循环结束时会发生什么?

Python:合并理货数据

perl - 列出类的实例对象

perl - 在 Perl 中传递标量引用

perl:如何按顺序解析 xml 文件

java - 我将如何创建 "infinite"循环,直到用户决定退出?

perl - 只应定义两个参数之一