使用 autodie,你不需要檢查檔案 openclose 失敗
autodie
允許你使用檔案而無需顯式檢查開啟/關閉失敗
從 Perl 5.10.1 開始, autodie
pragma 已經在核心 Perl 中可用。使用時,Perl 會在開啟和關閉檔案時自動檢查錯誤。
下面是一個示例,其中讀取一個檔案的所有行,然後將其寫入日誌檔案的末尾。
use 5.010; # 5.010 and later enable "say", which prints arguments, then a newline
use strict; # require declaring variables (avoid silent errors due to typos)
use warnings; # enable helpful syntax-related warnings
use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding
use autodie; # Automatically handle errors in opening and closing files
open(my $fh_in, '<', "input.txt"); # check for failure is automatic
# open a file for appending (i.e. using ">>")
open( my $fh_log, '>>', "output.log"); # check for failure is automatic
while (my $line = readline $fh_in) # also works: while (my $line = <$fh_in>)
{
# remove newline
chomp $line;
# write to log file
say $fh_log $line or die "failed to print '$line'"; # autodie doesn't check print
}
# Close the file handles (check for failure is automatic)
close $fh_in;
close $fh_log;
順便說一句,你應該在技術上總是檢查 print
語句。許多人沒有,但是 perl
(Perl 直譯器)不會自動執行此操作,也不會執行此操作 。