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

Hi Monks!
My question is about how I could call a subroutine if the "die" gets called. I have a subroutine (&email_error) that sends me an email if the code breaks. I would like to have right after the die when the code fails, just want to know a good way to call the sub &email_error.
Thanks for the help.
sub feed { ...code... while($l < $2) { ...code... } die "Could not retreive data"; }

Replies are listed 'Best First'.
Re: die properly
by dragonchild (Archbishop) on May 12, 2005 at 18:08 UTC
    eval { &feed; }; if ( $@ ) { &email_error; }

    • In general, if you think something isn't in Perl, try it out, because it usually is. :-)
    • "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"
      I could use your code right after the sub &feed or inside the subroutine?
        &feed; is the call to the subroutine. You wrap the call in an eval-block and check $@ to see if the subroutine died or not.

        • In general, if you think something isn't in Perl, try it out, because it usually is. :-)
        • "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"
Re: die properly
by eibwen (Friar) on May 12, 2005 at 18:11 UTC

    Alternatively, you could create a local $SIG{__DIE__} handler, but make sure to consult the discussion in perlvar as well as die in perlfunc.

Re: die properly
by dynamo (Chaplain) on May 12, 2005 at 18:13 UTC
    Set $SIG{__DIE__} to be a reference to the function you want to call when it dies. Check out perlvar for more info.