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";
}