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

How can I return from subroutine using a signal handler, like when a SIGINT is received, the program won't exit, but more like 'return' from the current subroutine? Thanks

Replies are listed 'Best First'.
Re: Returning through signal
by bikeNomad (Priest) on Jul 23, 2001 at 21:00 UTC
    You can use die for this. You can make a handler for die like this:

    $SIG{__DIE__} = sub { # do something };
    Look at the perlvar manpage for discussions of the %SIG hash. Note that your die handler will also be called in the case of die from evals; you may need to check $^S for this (it will be true inside an eval).
Re: Returning through signal
by trantor (Chaplain) on Jul 26, 2001 at 14:24 UTC

    When you install a signal handler for SIGINT, the process won't terminate unless you request it explicitly (i.e. using exit).

    Try this:

    #!/usr/bin/perl -w use strict; my $interrupted = 0; sub handler { $interrupted = 1; } $SIG{INT} = \&handler; print "Sleeping, feel free to interrupt (normally ^C)\n"; sleep(10); print "Done, "; print $interrupted ? "interrupted" : "without interruptions", ".\n";

    Pressing ^C causes sleep to return earlier, but it does not end the process.

    -- TMTOWTDI