加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:21:45 所属栏目:大数据 来源:网络整理
导读:Perl的设计(或技术)原因是什么不能使用以下语法自动本地化$ _? while (HANDLE) {...} 哪个被重写为: while (defined( $_ = HANDLE )) {...} 所有隐式写入$ _的其他结构都以本地化的方式(对于/ foreach,map,grep)执行此操作,但使用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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读