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

I'm working on some code where I'd like to have an END block execute when my program exits prematurely.

Reading the perldocs I understand that END should execute no matter how the program finishes. However it doesn't seem to be working if someone ends the the program with CTRL-C. Here's a sample piece of code:
#!/usr/bin/perl use strict; while(1) { } END { print "Hello from the END block\n"; }
To end this code the user is forced to use CTRL-C but the print statement never happens. Am I reading the docs wrong and missing something. Is there a better way to execute some code if the program stops before I want it to?

Thanks in advance
Chris

Replies are listed 'Best First'.
•Re: END {} not executing
by merlyn (Sage) on Mar 24, 2002 at 23:55 UTC
Re: END {} not executing
by Dog and Pony (Priest) on Mar 24, 2002 at 22:19 UTC
    See perlipc for ways to trap CTRL-C.

    Quote from the Camel book: END blocks are skipped only if you exec or your process is blown away by an uncaught catastrophic error.

    I guess you could call CTRL-C a catastrophic error, although I would go a bit easier on the words for such a common visitor... :)

    But to be serious, END and DESTROY blocks for instance, are skipped when you press CTRL-C. I think it is called the signal INT and it is a "fatal" signal for your program, so it promptly exits right away, no matter what it was doing, and without cashing in the $200.

    Hope that helps.


    You have moved into a dark place.
    It is pitch black. You are likely to be eaten by a grue.
Re: END {} not executing
by zengargoyle (Deacon) on Mar 24, 2002 at 22:08 UTC
    perl -e'$|++;$SIG{INT}=sub{exit};while(1){sleep 1;print "."}END{print" +done\n"}'

    See: perlipc