(空?)读取线的返回没有被控制结构捕获

Dav*_*vid 2 perl for-loop if-statement filehandle

我有一个包含打开的文件句柄的多维哈希,SEEK_END目的是始终读取最新的行而不需要太多的I/O(我会得到的tail).

我现在通过for循环遍历所有这些句柄并调用readline它们.

它看起来像这样:

for $outer ( keys %config ) {

    my $line = readline($config{$outer}{"filehandle"});

    if (not defined $line || $line eq '' ){
        next;
    }
    else{
        print "\nLine: -->".$line."<--\n";
        $line =~ m/(:)(\d?\.?\d\d?\d?\d?\d?)/;
        $wert = $2;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果将新内容写入这些文件,我的脚本会读取它并按照计划行事.

问题是,readline通常会返回任何结果,因为目前还没有在文件的结尾,但我if似乎并没有确定的空返readlineundef为空-它只是打印什么,这是因为没有将正确的这个字符串中没有任何内容,但我根本不希望它被处理.

Bor*_*din 6

这是运算符优先级问题.您使用了低优先级not和高优先级的混合物,||因此您的条件

not defined $line || $line eq ''
Run Code Online (Sandbox Code Playgroud)

被解析为

not(  defined($line)  ||  ($line eq '')  )
Run Code Online (Sandbox Code Playgroud)

这错误地否定了这一$line eq ''部分

它通常是使用更安全的低优先级的andor,和not&&,||!,而是一种混合物是非常糟糕的主意

你也可以写

if (not defined $line or $line eq '' ) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

要么

if ( ! defined $line || $line eq '' ) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

一切都会好的


我希望看到它写得像这样,因为它丢失了不必要的else子句和next语句,并丢弃了只包含空格字符的行

还要注意我迭代values哈希.当它们仅用于访问值时,使用密钥是浪费的.您可能会想到循环控制变量的更好名称$item

当Perl将变量直接插入到双引号字符串中时,通常不需要连接运算符

for my $item ( values %config ) {

    my $line = readline( $item->{filehandle} );

    if ( defined $line and  $line =~ /\S/ ) {

        print "\nLine: -->$line<--\n";

        $line =~ m/(:)(\d?\.?\d\d?\d?\d?\d?)/;
        $wert = $2;
    }
}
Run Code Online (Sandbox Code Playgroud)