http://qs321.pair.com?node_id=297534

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

Please advise how I can call a subroutine in a die statement. I have a mail subroutine that I want to call if a file doesnt open and I want to get the error message to print out in my STDERR.
This is not working but this is what Iam trying to do:
sub mysub { mail stuff here.. } open(TMPFILE,"<datafile.txt") || die "Cant open: $!" mysub();

Replies are listed 'Best First'.
Re: die and subroutine combo
by broquaint (Abbot) on Oct 08, 2003 at 11:08 UTC
    You could just use a simple do e.g
    open(TMPFILE,"<datafile.txt") or do { mysub(); die "Cant open: $!" };
    Or if you want it performed across the board you could create a die signal handler e.g
    $SIB{__DIE__} = sub { mysub(); die @_ };
    See. the die docs for more info.
    HTH

    _________
    broquaint

Re: die and subroutine combo
by bart (Canon) on Oct 08, 2003 at 11:10 UTC
    Perhaps you could set $SIG{__DIE__}. Like this:
    sub mysub { my $error = shift; print STDERR "mail stuff here..\n"; print STDERR "Error message: $error"; print STDERR "End of mail\n"; die $error; } local $SIG{__DIE__} = \&mysub; open(TMPFILE,"<datafile.txt") || die "Cant open: $!";
Re: die and subroutine combo
by crouchingpenguin (Priest) on Oct 08, 2003 at 13:22 UTC

    Simply use the comma operator between your die and your call to mysub() like so:

    sub mysub { mail stuff here.. } open(TMPFILE,"<datafile.txt") || die "Cant open: $!", mysub();

    cp
    ----
    "Never be afraid to try something new. Remember, amateurs built the ark. Professionals built the Titanic."
Re: die and subroutine combo
by flounder99 (Friar) on Oct 08, 2003 at 12:32 UTC
    You can do a simple concat. If you put any print statements in the sub they will be printed before the other error message (when the sub is called). This way you don't have to screw arround with signal handlers.
    sub mysub { print STDERR "This is printed before the error message.\n"; return "\nThis is printed in the middle of the error message."; } open(TMPFILE,"<datafile.txt") || die "Cant open: $!" . mysub();
    outputs:
    This is printed before the error message. Cant open: No such file or directory This is printed in the middle of the error message. at temp.pl line 6.

    --

    flounder