Copy all output of a perl script into a file

perl

Solution

Please see section "13.15.9. Tie Example: Multiple Sink Filehandles" in the Perl cookbook.

The main thing to know is `tie *TEE, "Tie::Tee", @handles;`

NOTE: Tie::Tee package is something you need to create yourself, the code is in that same section in the book.

NOTE: you can then do `select(TEE)` and it will be used in every regular `print` statement, so you don't need to do `print TEE xxx`.

NOTE: To have any STDERRy output (including die) go to the same filehandle, change the STDERR to TEE like this:

use Tie::Tee; 
use Symbol; 
@handles = (*STDOUT); 
push(@handles, $handle = gensym( )); 
open($handle, ">/tmp/teetest.xxx"); 
tie *TEE, "Tie::Tee", @handles; 
select(TEE); 
*STDERR = *TEE; 
print "raw print\n"; 
die "XXXX\n";

The output will be:

raw print
XXXX

And the file contents will be:

raw print
XXXX

Problem

I would like to copy stdout and stderr of my Perl script to a file, while retaining it also onscreen, and preferrably using some trick inside the script itself. I.e. I want something similar to ``` ./test.pl 2>&1 | tee foo.bar ``` but hidden inside the perl script implementation. For the moment I've just written a subroutine which prints all messages both onscreen and to a filehandle, but the drawback is that if the script dies, the die message will not appear in the log. Is there a way to do it?

Original source