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值.
相反,$_是单元化的,我得到一个“未初始化的值$_在模式匹配”(和打印)消息.
任何想法为什么会这样?
一个
解决方法
$_仅在您使用表单而不是(< $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.