Perl:意外的 $_ 行为

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

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

取而代之的是 $_ 被统一化,我收到了大量“模式匹配中的未初始化值 $_”(和打印)消息。

任何想法为什么会发生这种情况?

一种

最佳答案

$_仅在您使用表单 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

来自 perlop文档:

Ordinarily you must assign the returned value to a variable, but there is one situation where an automatic assignment happens. If and only if the input symbol is the only thing inside the conditional of a while statement (even if disguised as a for(;;) loop), the value is automatically assigned to the global variable $_, destroying whatever was there previously.

关于Perl:意外的 $_ 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9889222/

相关文章:

html - 将 Template Toolkit 用于纯 .html 文件?

perl - 尝试在 Perl 中使用 splice 删除特定列

Java perl文件删除/删除超过n天的文件

perl - 如何使脚本在IPv6地址上工作

arrays - Perl:合并哈希元素

regex - 我可以使用交替将多少个正则表达式链接在一起?

c - Perl 和外部程序

regex - perl 正则表达式,删除捕获的内容

arrays - 如何在给定键数组的情况下快速过滤散列?

perl - 基于文本代码的 awk/Perl/Sed 列替换