Search code examples
perldieperl-io

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


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?


Solution

  • Perl's die prints to STDERR so you could redirect STDERR to a file.

    #!/usr/bin/env perl
    # the path above depends on your system
    
    open(STDERR, ">>", "errlog.log");
    die "Hello";