Perl不使用以下语法自动本地化$_
的设计(或技术)原因是什么:
while (<HANDLE>) {...}
改写为:
while (defined( $_ = <HANDLE> )) {...}
所有其他隐式写入
$_
的构造都以本地化方式(for/foreach
,map
,grep
)这样做,但是对于while
,您必须显式本地化变量:local $_;
while (<HANDLE>) {...}
我的猜测是,它与在带有命令行开关的“Super-AWK”模式下使用Perl有关,但这可能是错误的。
因此,如果有人知道(或者更好的是参与了语言设计讨论),您能否与我们分享这种行为背后的原因?更具体地说,为什么尽管允许
$_
的值在循环外仍然存在,但仍然很重要(我倾向于在SO和其他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
andwhile
because they are two totally different things.foreach
always assigns to a variable when looping over a list, whilewhile
normally doesn't. It's just thatwhile (<>)
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/