views:

415

answers:

4

How can I print the output to terminal and file at the same time?

$ perl foo.pl > foout.txt

does not allow me to see live process.

Is there any way I can see the output process real time and getting at the end the output of the screen on a file?

+8  A: 

The utility tee will do that.

therefromhere
+1 to all; these answers complement each other perfectly :)!
Inshallah
+15  A: 

perl foo.pl | tee foout.txt

Draemon
So simple ! Thanks.
YoDar
Retagging your question as accepting this answer shows that this was not a Perl question.
Sinan Ünür
@Sinan: I'm adding the tag [perl] back in since people browsing the site for [perl] and [tee] should be able to find it either way. And as the responses make clear, you can do it with `tee` if it's available or within Perl itself (perhaps to make it more portable, etc.).
Telemachus
@Telemachus OK, makes sense.
Sinan Ünür
@Sinan: Nice edit, thanks.
Draemon
+7  A: 

See IO::Tee. This module will allow you to do this selectively with fine grained control within your program (there is also a less mature module called File::Tee which worked for me once but I would not recommend that for any serious project).

See also Log4perl for really fine grained control over what gets logged where and how.

For one off usage from the command line, as others have recommended, you can, of course, utilize the command line utility tee if you have access to it.

Sinan Ünür
I've always used IO::Tee for this sort of thing. If you have experience with both, how would you compare them. (I'm looking now at the docs for File::Tee, but I'm curious if you have any input.)
Telemachus
@Telemachus I have rarely used File::Tee and never used IO::Tee so I am not in a position to do a comparison between the two. File::Tee worked nicely when I needed it. On the other hand, Log4perl is wonderful.
Sinan Ünür
@Sinan: Fair enough. I will take a look at File::Tee and compare myself. I just figured I would ask.
Telemachus
@Telemachus My guess is I got lucky when I used it (it wasn't anything serious). If I ever said "oh where is tee for Perl" again, I would go with IO::Tee.
Sinan Ünür
@Telemachus Oh, I did not know File-Tee did not work on Windows. Goes to show you ... I am going to drop my recommendation for File::Tee.
Sinan Ünür
A: 

Or you could pipe it into a perl programs to print to the screen and a log file (that is if you are not on Unix or have a tee program)

perl foo.pl | perl myPipe.pl myFile.txt

where the data is captureed to myFile.txt and

myPipe.pl is

#
open OUTFILE,">$ARGV[0]" or die "Unable to open file: $ARGV[0]\n";

while(<>)
{
    print;
    print OUTFILE;
}
close OUTFILE;

This reads a line of input from STDIN and prints it to the screen and then to the file. When the end is reached, it will close the file

Glenn