Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect output of die function to a file in Perl?

Tags:

die

perl

perl-io

I want to redirect the die messages to a separate file so that I can compare that file later to determine what went wrong.

But this code gives me errors:

$ cat test.pl
use strict;
use warnings;

my $log = "msglog.log";
die $log "DEAD$!";

$ perl test.pl
Missing comma after first argument to die function at test.pl line 5, near ""DEAD$!";"
Execution of test.pl aborted due to compilation errors.
$ 

I do not want to do a 2> from the caller. Is there someway to redirect them from within the script?

like image 475
Lazer Avatar asked Oct 15 '10 06:10

Lazer


1 Answers

You can install a $SIG{__DIE__} handler to be run just before the "die" runs. The handler will be called with the error message which you can log:

local $SIG{__DIE__} = sub {
    my ($message) = @_;
    # log the message        
};

See $SIG{expr} in perlvar for details.

like image 69
Eugene Yarmash Avatar answered Sep 19 '22 02:09

Eugene Yarmash