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

I know that it is possible to trap a number of signals in perl using the %SIG hash. However, I cannot find which specific signal would correspond to the self generated termination due to the execution of the exit() function. In other words, I'm trying to define an event to be performed whenever the program exits normally. Is this possible using the %SIG hash? If not, how can I do this?

Thanks as always!

Replies are listed 'Best First'.
Re: trapping exit() calls with %SIG
by kennethk (Abbot) on Jul 14, 2010 at 15:35 UTC
    The normal way to call code on program exit is to use an END block. This, as well as its compatriots BEGIN, UNITCHECK, CHECK, and INIT, is discussed in BEGIN, UNITCHECK, CHECK, INIT and END in perlmod. If this does not look like it meets your spec, expound upon your specific circumstances and we'll see if we can help.

    #!/usr/bin/perl use strict; use warnings; sub END { print "I ended\n"; }
      thank you. That's what I was looking for.
Re: trapping exit() calls with %SIG
by ikegami (Patriarch) on Jul 14, 2010 at 16:52 UTC

    I'm trying to define an event to be performed whenever the program exits normally

    Aforementioned END is definitely the way to go. To have your code only execute when the program exits normally, use a flag.

    my $exited_normally = 0; ... # At the end of the progam. $exited_normally = 1; END { return if !$exited_normally; ... }

    just put your cleanup code (or a call to your cleanup code) at the end of the program.

    Update: It's silly to both use END and to require code at the end of the program.