Perl的设计(或技术)原因是什么不能使用以下语法自动本地化$ _?
while (<HANDLE>) {...}
哪个被重写为:
while (defined( $_ = <HANDLE> )) {...}
所有隐式写入$ _的其他结构都以本地化的方式(对于/ foreach,map,grep)执行此操作,但使用while时,必须显式地本地化变量:
local $_; while (<HANDLE>) {...}
我的猜测是它与使用Perl在“Super-AWK”模式与命令行开关有关,但这可能是错误的。
所以如果有人知道(或更好地参与语言设计讨论),那么你能与我们分享这个行为背后的原因吗?更具体地说,为什么允许$ _的值保持在循环之外被认为是重要的,尽管它可能导致错误(我倾向于在SO和其他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
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.