2012-11-02 47 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