Run a code block when the program is shutting down.
END { ... } registers a block to be executed when the Perl interpreter is exiting, after the main program has finished but before global destruction tears down package storage. It is the canonical place to put cleanup code such as closing log files, removing temporary directories, or flushing outstanding statistics.
Multiple END blocks run in reverse order of their declaration, mirroring a stack. They run even if the program exits abnormally via die, but not if the process is killed by an uncatchable signal or if it calls POSIX::_exit.
Within an END block, $? holds the program's prospective exit status; setting it changes what the interpreter ultimately reports. The $0 program name and global state are still available, making END useful for last-chance reporting.
| Name | Description | Optional |
|---|---|---|
BLOCK |
The braced block of code to execute at program shutdown. | No |
my $tmp = "/tmp/work.$$";
mkdir $tmp;
END {
unlink glob "$tmp/*";
rmdir $tmp;
}
END { warn "exiting with status $?\n" }