为什么 Perl 的 eval 不能捕获 Test::Cmd::Common->unlink 中的问题?

发布于 2024-08-17 17:39:13 字数 684 浏览 3 评论 0原文

我有以下 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。

I have the following perl code :

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";

The $test->unlink() line will fail and throw exception. but the problem : eval is not handling that exception and the code execution is being interrupted.

the output :

$ 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.

Is eval doing the right job here? or I am misunderstanding something?

F.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月光色 2024-08-24 17:39:13

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

exit (2);

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

From documentation of Test::Cmd::Common: "Removes the specified files. Exits NO RESULT if any file could not be removed for any reason.". And by looking at source, Test::Cmd::Common calls Test::Cmd->no_result, which really does

exit (2);

"exit" cannot be trapped by eval, so it is expected behavior.

z祗昰~ 2024-08-24 17:39:13

这有点正交,但如果您想测试操作是“成功”还是失败,请使用 测试::异常:

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';

This is slightly orthogonal, but if you want to test if an operation "succeeded" or died, use 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';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文