From: PerlFAQ Server on
This is an excerpt from the latest version perlfaq8.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at .


8.18: How can I do an atexit() or setjmp()/longjmp()? (Exception handling)

You can use the "END" block to simulate "atexit()". Each package's "END"
block is called when the program or thread ends See perlmod manpage for
more details about "END" blocks.

For example, you can use this to make sure your filter program managed
to finish its output without filling up the disk:

close(STDOUT) || die "stdout close failed: $!";

The "END" block isn't called when untrapped signals kill the program,
though, so if you use "END" blocks you should also use

use sigtrap qw(die normal-signals);

Perl's exception-handling mechanism is its "eval()" operator. You can
use "eval()" as "setjmp" and "die()" as "longjmp". For details of this,
see the section on signals, especially the time-out handler for a
blocking "flock()" in "Signals" in perlipc or the section on "Signals"
in *Programming Perl*.

If exception handling is all you're interested in, use one of the many
CPAN modules that handle exceptions, such as "Try::Tiny".

If you want the "atexit()" syntax (and an "rmexit()" as well), try the
"AtExit" module available from CPAN.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in