Re: capture output in perl

From: Ankur Gupta (Ankur.Gupta_at_synopsys.com)
Date: 02/28/05


Date: Mon, 28 Feb 2005 19:40:49 +0530
To: geraldine_1@comcast.net

geraldine_1@comcast.net wrote:

>hi,
>I would like to capture all the output in my perl program during execution. I have code that basically opens and closes an output file multiple times just to write the output. Because I have system calls between lines of code, I have to close the file in order to capture the output from the system calls and write it to the same file (in this case /tmp/tmp.log) .
>
>Not an elegant code. Is there a better way of rewriting the code?
>
Add this to the top:

$| = 1; (To flush the output so that the order of print statement is maintained)
open(STDSAVE, ">&STDOUT"); # Duplicate your STDOUT filehandle incase you want to print something on the screen.
open(STDOUT,">>/tmp/tmp.log"); # Open your log file with STDOUT as the filehandle

#Everything that you print now would go to log file now.
#Along with the output of the system command.

#Now remove all instances of OUTF from the code.
        print OUTF "i=10\n\n";
to
                print "i=10\n\n";
#Also remove all redirection of the your system commands output to the log file
        system ("ls nofile.txt 2>> /tmp/tmp.log");
to
        system ("ls nofile.txt 2");

Incase you want to print to the screen.
Use print STDSAVE "HEllo there\n"; # Would print on the screen.
In case you want to close the log file and restore to the normal printing.
close(STDOUT);
open(STDOUT,">&STDSAVE);

One more thing: If you want to print your output to the screen as well as to the log file.
Use open(STDOUT, "| tee /tmp/tmp.log STDOUT");
So whatever you print would go to the screen as well as to the log file. (--> Taken from Perl Cookbook)

Same you can do with the STDERR to capture your warnings and errors to a separate error log file.

HTH

--
Ankur