next up previous contents
Next: Objects in Perl Up: Signals Previous: Signals

How to Handle a Signal

You can cause Perl to ignore the Ctrl+C key sequence by placing the following line of code near the beginning of your program:


You can restore the default handler like this:


If you need to ensure that files are closed, error messages are written, or other cleanup chores are completed, you need to create a custom INT handle function. For example:

sub INT_handler {

    # close all files.

    # send error message to log file.



$SIG{'INT'} = 'INT_handler';

If the Ctrl+C key sequence is pressed anytime after the hash assignment is made, the INT_handler function is called instead of the default handler.

Note In theory, you could remove the exit() call from the signal handler function, and the script should start executing from wherever it left off. However, this feature is not working on several platforms. If you want to test your platform, run the following small program:

sub INT_handler {
             print("Don't Interrupt!\n");

         $SIG{'INT'} = 'INT_handler';
         for ($x = 0; $x < 10; $x++) {
             sleep 1;

You should be able to press Ctrl+C while the script is counting without forcing the script to end.

The %SIG associative array holds only entries you have created for your custom signal handler functions. So, unfortunately, you can't find out which signals are supported by looking at the array returned by keys(%SIG).


If you are running Perl on a UNIX machine, you can run the kill -l command. This command displays a list of possible signals.

The port of Perl for Win32 supports the following signals:

You can also use the %SIG hash to trap a call to the warn() and die() functions. This comes in handy if you're working with someone else's code and want to keep a log of whenever these functions are called. Rather than finding every place the functions are used, you can define a handler function as follows:

The Perl implementation is as follows

sub WARN_handler {

    my($signal) = @_;

    sendToLogfile("WARN: $signal");


sub DIE_handler {

    my($signal) = @_;

    sendToLogfile("DIE: $signal");


sub sendToLogfile {

    my(@array) = @_;

    open(LOGFILE, ">>program.log");

    print LOGFILE (@array);



$SIG{__WARN__} = 'WARN_handler';

$SIG{__DIE__}  = 'DIE_handler';

chdir('/printer') or warn($!);

chdir('/printer') or die($!);

When this program is done executing, the PROGRAM.LOG file contains these lines:

WARN: No such file or directory at line 22.
DIE: No such file or directory at line 23.

next up previous contents
Next: Objects in Perl Up: Signals Previous: Signals