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

I have a script that outputs everything on STDOUT. It also uses 'do "filename.pl"' a bunch of times, which all output on STDOUT. Is there a simple way I can change the output to a file for all output (even in the do's)? I know I can redirect from my shell by "script.pl >someplace", but if it can be contained in the script, that would be great! Any help would be great, thanks!

Replies are listed 'Best First'.
Re: redirect all output
by Joost (Canon) on Apr 28, 2005 at 14:33 UTC
Re: redirect all output
by ihb (Deacon) on Apr 28, 2005 at 14:35 UTC

    You can duplicate STDOUT and then reopen STDOUT to something else.

    open my $stdout, '>&STDOUT' or die $!; open STDOUT, '>', $file or die $!;
    Now everything printed to STDOUT ends up in the file given by $file. If you want to print to the original STDOUT you can do that by doing print $stdout 'hello';.

    See perlopentut for more on this.

    ihb

    See perltoc if you don't know which perldoc to read!

Re: redirect all output
by blazar (Canon) on Apr 28, 2005 at 14:42 UTC
    In addition to the answers you already received, see also select.
Re: redirect all output
by polettix (Vicar) on Apr 28, 2005 at 14:45 UTC
    Note that if you intend to redirect to an in-memory variable (Perl 5.8.x) you have to close STDOUT first; from perldoc -f open:
    File handles can be opened to "in memory" files held in Perl scalars via:
    open($fh, '>', \$variable) || ..
    Though if you try to re-open "STDOUT" or "STDERR" as an "in memory" file, you have to close it first:
    close STDOUT; open STDOUT, '>', \$variable or die "Can't open STDOUT: $!";

    Flavio (perl -e 'print(scalar(reverse("\nti.xittelop\@oivalf")))')

    Don't fool yourself.
Re: redirect all output
by tlm (Prior) on Apr 28, 2005 at 14:38 UTC

    What I would do is:

    open my $hold, '>&', STDOUT or die "Failed to dup STDOUT\n"; open STDOUT, '>', 'output.txt' or die "Failed to re-open STDOUT\n"; # later, if you want to restore STDOUT: open STDOUT, '>&', $hold or die "Failed to restore STDOUT\n";
    The only line you really need is the second open. The first and the third opens are there only in case you want to restore STDOUT to its original state.

    the lowliest monk