Perl:意外的$ _行为

时间:2012-03-27 12:06:14

标签: 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;
}

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

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

为什么会这样?

A

1 个答案:

答案 0 :(得分:20)

$_仅在您使用while (<$fh>)表单时设置,而您不是。{/ p>

看看这个:

$ 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

来自perlop文档:

  

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