perl - 在Perl中,为什么 `while(<HANDLE>) {…}`构造不本地化 `$_`?

标签 perl language-design while-loop local

Perl不使用以下语法自动本地化$_的设计(或技术)原因是什么:

while (<HANDLE>) {...}

改写为:
while (defined( $_ = <HANDLE> )) {...}

所有其他隐式写入$_的构造都以本地化方式(for/foreachmapgrep)这样做,但是对于while,您必须显式本地化变量:
local $_;
while (<HANDLE>) {...}

我的猜测是,它与在带有命令行开关的“Super-AWK”模式下使用Perl有关,但这可能是错误的。

因此,如果有人知道(或者更好的是参与了语言设计讨论),您能否与我们分享这种行为背后的原因?更具体地说,为什么尽管允许$_的值在循环外仍然存在,但仍然很重要(我倾向于在S​​O和其他Perl代码中经常看到这种错误),但为什么它仍然很重要?

如果以上内容不清楚,则在此示例中显示必须用$_本地化while的原因:
sub read_handle {
    while (<HANDLE>) { ... }
}

for (1 .. 10) {
     print "$_: \n"; # works, prints a number from 1 .. 10
     read_handle;
     print "done with $_\n";  # does not work, prints the last line read from
                              # HANDLE or undef if the file was finished
}

最佳答案

在perlmonks.org上的thread中:

There is a difference between foreach and while because they are two totally different things. foreach always assigns to a variable when looping over a list, while while normally doesn't. It's just that while (<>) is an exception and only when there's a single diamond operator there's an implicit assignment to $_.



并且:

One possible reason for why while(<>) does not implicitly localize $_ as part of its magic is that sometimes you want to access the last value of $_ outside the loop.

关于perl - 在Perl中,为什么 `while(<HANDLE>) {…}`构造不本地化 `$_`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5505150/

相关文章:

perl - 在perl中解析不规则命令的输出

regex - 匹配反斜杠后跟转义字符

javascript - 是否有一个 javascript (jquery) 库用于从 cgi 参数更新 html 表单控件?

scheme - 了解 MIT Scheme 中的 block 结构

refactoring - 有助于重构的编程语言属性?

perl - 将数据结构转化为perl对象(模块推荐)

language-agnostic - 为什么默认情况下语言不会引发整数溢出错误?

python - 从 Python 到 R 的翻译。执行时间差异很大

java - 无法让循环正常工作

c - 无法完全执行 do-while 循环