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
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.
原文地址:https://www.jb51.cc/Perl/173197.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。