在Perl中,为什么`while(){…}构造不是本地化`$_`?

Perl的设计(或技术)原因是什么不能使用以下语法自动本地化$ _?
while (<HANDLE>) {...}

哪个被重写为:

while (defined( $_ = <HANDLE> )) {...}

所有隐式写入$ _的其他结构都以本地化的方式(对于/ foreach,map,grep)执行此操作,但使用while时,必须显式地本地化变量:

local $_;
while (<HANDLE>) {...}

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

所以如果有人知道(或更好地参与语言设计讨论),那么你能与我们分享这个行为背后的原因吗?更具体地说,为什么允许$ _的值保持在循环之外被认为是重要的,尽管它可能导致错误(我倾向于在S​​O和其他Perl代码中看到所有的地方)?

如果从上面不清楚,本例中显示了$ _必须本地化的原因:

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
}

解决方法

thread在perlmonks.org:

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.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...