Files
如何使用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
,對嗎?還是錯了?
您缺少 a
-z
和$
in-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