为什么 Perl 的 eval 不能捕获 Test::Cmd::Common->unlink 中的问题?
我有以下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 Test::Cmd::Common 的文档:“删除指定的文件。如果由于任何原因无法删除任何文件,则退出无结果。”。通过查看源代码,Test::Cmd::Common 调用 Test::Cmd->no_result,这实际上确实
“退出”不能被 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" cannot be trapped by eval, so it is expected behavior.
这有点正交,但如果您想测试操作是“成功”还是失败,请使用 测试::异常:
This is slightly orthogonal, but if you want to test if an operation "succeeded" or died, use Test::Exception: