如何忽略 perl 子例程上的 exit(1) - 试过 eval 但没有用

How to ignore an exit(1) on a perl subroutine - tried eval but didn't work

我正在尝试对遗留代码进行小的修复,因此我无法更改子例程方法 (&my_subroutine)。问题是在某些情况下子例程会调用“exit(1)”,这只会停止脚本执行。我只想忽略它并继续循环,但如果有错误也会捕获并使用另一个子例程调用。这可能吗?

这是我试过的:

foreach my $l_host (keys %a_results)
{
    # Check if a specific configuration is in place for the host
    $server = substr($l_host, 0, index($l_host, ':'));

    # Test if the configuration exists
    eval {
        &my_subroutine($server);
        # My script ends right here if there's a "exit(1)" above 
    };

    if (not $@) # Found a specific configuration for this server
    {
        $specific_keytool = &my_subroutine($server);
        $g_command =~ s/$keytoolExe/$specific_keytool/g;
    }
    else # If didn't find a config, use the default one.
    {
        # Make sure that the default one is being used
        $g_command =~ s/$specific_keytool/$keytoolExe/g;
    }
    # End
    #
    # Continue doing other stuff...

perlmonks link 对此有所提示,但您可以覆盖许多 Perl 的内置函数,包括 exit。这是一种可能的结构方式:

our $TRAP_EXIT = 0;
BEGIN {
    *CORE::GLOBAL::exit = sub {
        my $exit_code = $_[0] || 0;
        if ($TRAP_EXIT) {
            die "exit($exit_code) call trapped!";
        } else {
            CORE::exit($exit_code);
        }
    };
}

...

{
    local $TRAP_EXIT = 1;
    eval { &subroutine_that_might_call_exit() };
    ...
}