Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Run before exit

by Delusional (Beadle)
on Jun 16, 2008 at 15:55 UTC ( [id://692291]=perlquestion: print w/replies, xml ) Need Help??

Delusional has asked for the wisdom of the Perl Monks concerning the following question:

Hi, is there a way to 'inject' something into the exit(); function? Basically, I want to ensure a sub runs, even if an exit; is called.

Yes, I know I can make a sub that will ensure the desired sub is called, then call exit, however, if someone adds coding to the application and calls exit; then, essentially, Perl exits, without running the code. Is there anyway to ensure something runs if exit; is called? Something like $SIG{__DIE__} and $SIG{__WARN__}, but only if exit; is called. Obviously, if the application exits normally, the code will have executed, and does not need to, and should not, execute again.

Replies are listed 'Best First'.
Re: Run before exit
by pileofrogs (Priest) on Jun 16, 2008 at 16:47 UTC

    You could use an END block or $SIG{__DIE__} and then use caller to find out if you're END'ing or DIE'ing from an exit call.

      Thanks. This got me on the right track. Simply adding a sub END { } did the trick. I had to change the ending sub to set a var, and only execute if the var wasn't set though. Waisted memory and not really the cleanest way, and I, possibly, could have put the entire ending sub in the END sub, but it works.

      The original ending sub was all that needed to be executed as its basically a 'clean-up and close loose ends' function (database, file handlers, html footers, etc.).

      I intentionally placed exit calls in bad places to test if all was working correctly, and it did with sub END { }, but 'failed' (because the ending sub was not executed) without it.
Re: Run before exit
by moritz (Cardinal) on Jun 16, 2008 at 16:00 UTC
    Just add a block like this:
    END { call_your_sub_here() }

      Wouldn't that be executed as well with die()?

      --
      b10m
        Yes. I didn't parse the "only" in the original question correctly. If it should really only be triggered by exit, it might be useful to override it (CORE::exit IIRC).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://692291]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-19 04:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found