Perl Signals

Perl Signals

Perl allows you to trap signals using the %SIG associative array. Using the signals you want to trap as the key, you can assign a subroutine to that signal. The %SIG array will only contain those values which the programmer defines. Therefore, you do not have to assign all signals. For example, to exit cleanly from a ^C:

 $SIG{'INT'} = 'CLEANUP';  sub CLEANUP {     print "Caught Interrupt (^C), Aborting\n";     exit(1); }  

There are two special “routines” for signals called DEFAULT and IGNORE. DEFAULT erases the current assignment, restoring the default value of the signal. IGNORE causes the signal to be ignored. In general, you don’t need to remember these as you can emulate their functionality with standard programming features. DEFAULT can be emulated by deleting the signal from the array and IGNORE can be emulated by any undeclared subroutine.


In 5.001, the $SIG{__WARN__} and $SIG{__DIE__} handlers may be used to intercept die() and warn(). For example, here’s how you could promote unitialized variables to trigger a fatal rather merely complaining:

   #!/usr/bin/perl -w   require 5.001;  $SIG{__WARN__} = sub {     if ($_[0] =~ /uninit/) {         die $@;     } else {         warn $@;     } };  
If you have found my website useful, please consider buying me a coffee below 😉