应尽快删除2

时间:2016-12-10 03:00:35

标签: perl eval

应该尽快删除,因为它不再可用

1 个答案:

答案 0 :(得分:3)

由于第二组调用不在eval

,因此甚至无效
for (my $num_tries = 3; ; ) {
    last if eval {
        my $stuff1 = function1();
        my $stuff2 = function2();
        function3();
        return 1;  # No exception.
    };

    --$num_tries
        or die($@);

    chomp( my $e = $@ );
    warn("$e Retrying...");
}

function4();

以上内容将function3();移至eval。如果你想允许它抛出异常(或者它真的是returnlast等),你可以使用以下代码:

my $num_tries = 3;
while (1)
    last if eval {
        my $stuff1 = function1();
        my $stuff2 = function2();
        return 1;  # No exception.
    } || !--$num_tries;

    chomp( my $e = $@ );
    warn("$e Retrying...");
}

if ($num_tries) {
    function3();
} else {
    warn($@);
}

function4();

这再次变得有点复杂,所以让我们使用一个子!

sub non_fatal_retry(&$) {
    my ($cb, $num_tries) = @_

    while (!eval { $cb->(); 1 }) {
        --$num_tries
            or warn($@), return 0;

        chomp( my $e = $@ );
        warn("$e Retrying...");
    }

    return 1;
}

解决方案变为:

if (non_fatal_retry {
    my $stuff1 = function1();
    my $stuff2 = function2();
}, 3) {
    function3();
}

function4();