加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl:意外的$_行为

发布时间:2020-12-15 21:52:44 所属栏目:大数据 来源:网络整理
导读:use Modern::Perl;use DateTime;use autodie;my $dt;open my $fh,'','data.txt';# get the first date from the filewhile ($fh !$dt) { if ( /^(d+:d+:d+)/ ) { $dt = DateTime-new( ... ); } print;} 我期待这个循环读取文件的每一行,直到读取第一个dat
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读