如何使用if条件在perl中检查2个文件是否为空

如何使用if条件在perl中检查2个文件是否为空
if(-z "$file1" && "file2") {
  print "file1 and file2 are empty";
} else {
 print "execute";
}

当我写这个时,当文件为空时,它会打印execute,当文件不为空时,它会打印 file1 and file2 are empty

当条件为真时,应该打印file1 and file2 are empty,我说得对吗?还是错了?

答案1

您缺少a-z$-z "$file2"另外,您不需要引用文件名(但这不会导致错误)。使用 Perl 单行代码作为示例运行以下测试:


rm -rf foo bar
touch foo
perl -le 'my $file1 = "foo"; my $file2 = "bar"; if ( -z $file1 && -z $file2 ) { print "file1 and file2 are empty"; } else { print "execute"; }'
# File 'bar' does not exist, so -z $file2 evaluates to false:
# execute

rm -rf foo bar
touch foo bar
perl -le 'my $file1 = "foo"; my $file2 = "bar"; if ( -z $file1 && -z $file2 ) { print "file1 and file2 are empty"; } else { print "execute"; }'
# Both files exist and are zero size, so both '-z' tests evaluate to true:
# file1 and file2 are empty

rm -rf foo bar
touch foo bar
echo '1' > bar
perl -le 'my $file1 = "foo"; my $file2 = "bar"; if ( -z $file1 && -z $file2 ) { print "file1 and file2 are empty"; } else { print "execute"; }'
# File 'bar' iz non-zero size, so -z $file2 evaluates to false:
# execute

答案2

-z您在声明中缺少一个if

if ( -z "$file1" && -z "$file2" ) {
    print "file1 and file2 are empty";
}
else {
    print "execute";
}

相关内容