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/