CN Perl Advent Calendar 2009-12-04

autodie

by Fayland Lam

在编写 Perl 脚本的时候,我们经常使用类似下面的代码来检查内置函数(如 open)是否成功。

open(my $fh, '<', $filename) or die "Can't open $filename - $!";

我们经常发现有太多地方需要重复写,或者经常遗忘了这样写。想偷懒?找 autodie.

   1 eval {
   2     use autodie;
   3     open(my $fh, '<', $some_file);
   4     my @records = <$fh>;
   5     # Do things with @records...
   6     close($fh);
   7 };
   8 
   9 if ($@ and $@->isa('autodie::exception')) {
  10     if ($@->matches('open')) { print "Error from open\n";   }
  11     if ($@->matches(':io' )) { print "Non-open, IO error."; }
  12 } elsif ($@) {
  13     # A non-autodie exception.
  14 }

autodie 不仅仅对系统函数起作用,还可以对自定义函数其作用。

use File::Copy qw(move);
use autodie qw(move);

move('noexists.txt', 'another.txt');

当移动失败时会自动报错,如

Can't move('noexists.txt', 'another.txt'): Bad file descriptor at t.pl line 9

更多的请参考 autodie doc 和 Perl Training Australia - autodie

谢谢。

View Source (POD)