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 }
解决方法
There is a difference between @H_403_26@foreach
and @H_403_26@while because they are two totally
different things. @H_403_26@foreach always
assigns to a variable when looping
over a list,while @H_403_26@while normally
doesn’t. It’s just that @H_403_26@while (<>) is
an exception and only when there’s a
single diamond operator there’s an
implicit assignment to @H_403_26@$_.
并且:
One possible reason for why @H_403_26@while(<>)
does not implicitly localize @H_403_26@$_ as
part of its magic is that sometimes
you want to access the last value of
@H_403_26@$_ outside the loop.