我完全困惑。这里是我的代码:为什么两个分支似乎都执行?
use strict;
use warnings;
use Test::More;
subtest 'huh?' => sub {
my $i = 0;
eval {
$i++;
} || do {
$i++;
};
is($i, 1, "only execute one branch (i: $i)");
};
&done_testing();
这是我的测试输出(用时5.12的activeperl运行的Mac OS X):
not ok 1 - only execute one branch (i: 2)
# Failed test 'only execute one branch (i: 2)'
# at test.pl line 14.
# got: '2'
# expected: '1'
1..1
# Looks like you failed 1 test of 1.
not ok 1 - huh?
# Failed test 'huh?'
# at test.pl line 15.
1..1
# Looks like you failed 1 test of 1.
这到底是怎么回事?我预计只有第一个分支才能运行,因为没有任何die
s。但它看起来像两个分支都被执行。
啊...所以当我使用'eval'来捕获异常时,我应该始终确保它返回一个真值,以免在'eval'内部抛出异常? – 2012-03-14 20:09:20
@MattFenwick,如果你打算用'||'或者'or'测试返回,那么是的。我要更新我的答案。 – Axeman 2012-03-14 20:12:03
如果你在修正bug之前运行一个perl版本,'if $ $'语句有机会运行之前'$ @'可以在'DESTROY'块中清除。 'eval {...; 1}或呱呱叫......'不会受到这个错误的影响。 – 2012-03-14 21:47:22