为什么Perl的eval没有从Test :: Cmd :: Common-> unlink中捕获问题?

时间:2010-01-12 10:32:10

标签: perl eval

我有以下perl代码:

use strict;
use warnings;
use Test::Cmd::Common;

my $path = "/something/not/available";
my $test = Test::Cmd::Common->new(string => 'File system operations');

eval{
        $test->unlink("$path");
};
ok(!$@, "file unlike");

print "done.\n";

$ test-> unlink()行将失败并抛出异常。但问题是:eval没有处理该异常,代码执行正在被中断。

输出:

$ perl test.pl 
could not unlink files (/something/not/available): No such file or directory
NO RESULT for test at line 561 of /home/y/lib/perl5/site_perl/5.8/Test/Cmd/Common.pm (Test::Cmd::Common::unlink)
    from line 9 of test.pl.

eval在这里做得对吗?或者我误解了什么?

F。

2 个答案:

答案 0 :(得分:11)

从Test :: Cmd :: Common的文档:“删除指定的文件。如果因任何原因无法删除任何文件,则退出无结果。”。通过查看源代码,Test :: Cmd :: Common调用Test :: Cmd-> no_result,这确实是

exit (2);

“退出”不能被eval捕获,因此它是预期的行为。

答案 1 :(得分:1)

这稍微正交,但如果您想测试操作是否“成功”或死亡,请使用Test::Exception

use strict;
use warnings;
use Test::More tests => 2;
use Test::Exception;

note 'File system operations';
dies_ok
    { some_operation_which_may_die(); }
    'operation died';

throws_ok
    { some_operation_which_may_die(); }
    /String we expect to see on death/,
    'operation died with expected message';