perl 'last' 语句和变量作用域

perl 'last' statement and variable scope

本应是简单的 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 中的 "break" 或 Java 完全不同?

谢谢!

这不是 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).