Perl捕获运行时错误

时间:2012-11-02 09:24:11

标签: perl runtime try-catch

我正在编写一个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.

2 个答案:

答案 0 :(得分:1)

这些特定错误是由ARGV后面的“魔法”发送给STDERR的警告。你为什么不直接重定向STDERR?

perl script.pl foo bar 2>error.log

如果这还不够好,您必须开始使用$SIG{__WARN__}(yuck)或停止使用ARGV<>,没有文件句柄默认使用ARGV )。

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

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

答案 1 :(得分: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";
}