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

Viewed 114

I'm trying to make a small fix on a legacy code, so I can't change the subroutine method (&my_subroutine). The problem is that there are some situations that the subroutine will call "exit(1)" and this just stops the script execution. I'd like to just ignore this and continue a loop, but also catch if there's an error and use another subroutine call. Is this possible?

This is what I've tried:

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...
1 Answers

The perlmonks link hints at this, but you can override many of Perl's builtin functions, including exit. Here's one possible way to structure it:

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() };
    ...
}
Related