Perl:意外的$ _行为

Ric*_*ard 7 perl

use Modern::Perl;
use DateTime;
use autodie;

my $dt;

open my $fh, '<', 'data.txt';

# get the first date from the file
while (<$fh> && !$dt) {
   if ( /^(\d+:\d+:\d+)/ ) {
      $dt = DateTime->new( ... );
   }
   print;
}
Run Code Online (Sandbox Code Playgroud)

我期待这个循环读取文件的每一行,直到读取第一个datetime值.

相反,$ _是单元化的,我得到一个"未初始化的值$ _在模式匹配"(和打印)消息.

任何想法为什么会这样?

一个

Mat*_*Mat 20

$_仅在您使用表单while (<$fh>)表单时才设置,而您不是.

看这个:

$ cat t.pl
while (<$fh>) { }
while (<$fh> && !$dt) { }

$ perl -MO=Deparse t.pl
while (defined($_ = <$fh>)) {
    ();
}
while (<$fh> and not $dt) {
    ();
}
t.pl syntax OK
Run Code Online (Sandbox Code Playgroud)

来自perlop文档:

通常,您必须将返回的值分配给变量,但有一种情况会发生自动分配.当且仅当输入符号是while语句条件内唯一内容时(即使伪装成for(;;)循环),该值将自动分配给全局变量$ _,从而破坏之前的任何内容.