2012-11-02 43 views
1

我寫一個Perl腳本打開一個文本,並在其上進行一些轉換。當文本文件不可用時,腳本會拋出一個錯誤,指出「沒有這樣的文件或目錄存在」。Perl中捕獲運行時錯誤

我想抓住這個錯誤,並創建文本文件即可。

while (<>) {  #i am passing filename from the batch file 
    #some task 
} 
# if the above while loop fails it throws no such file or directory exists error. I want to catch it and do some other task. 

回答

1

這些特定錯誤是由「神奇」的背後ARGV發送到STDERR警告。你爲什麼不重定向STDERR?

perl script.pl foo bar 2>error.log 

如果這還不夠好,你就必須開始使用$SIG{__WARN__}(呸),或停止使用ARGV<>沒有文件句柄默認使用ARGV)。

for my $argv (@ARGV ? @ARGV : '-') { 
    open(my $argv_fh, $argv) 
     or do { 
      ... print message to log file ... 
      next; 
      }; 

    while (<$argv_fh>) { 
     ... 
    } 
} 
1

,而不是試圖趕上該文件不存在的警告,爲什麼不嘗試通過getopt和檢驗合格的文件路徑文件的存在/可讀性使用file test operators開幕之前。

編輯:用例更新

#!/usr/bin/perl 

use strict; 
use warnings; 
use Getopt::Std; 

my %opts; 
getopt('f', \%opts); 

die "use -f to specify the file" unless defined $opts{f}; 

if(! -e $opts{f}){ 
    print "file doesn't exist\n"; 
} 
elsif(! -r $opts{f}){ 
    print "file isn't readable\n"; 
} 
elsif(! -f $opts{f}){ 
    print "file is not a normal file\n"; 
} 
else{ 
    open(my $fh, '<', $opts{f}) or print "whatever error handling logic\n"; 
} 
+0

文件測試不會得到所有的錯誤。只有'open'纔是可靠的,在這一點上沒有理由使用'<>'。 – ikegami

+0

我想我誤解了這個問題,我把它看作'如果傳遞給腳本的文件名不存在,那麼創建該文件並執行其他邏輯,如果傳遞給腳本的文件確實存在,請執行其他操作'。不會提交適合的測試嗎? – beresfordt

+0

因爲無法檢查可讀性,對於初學者。 – ikegami