views:

44

answers:

1

Hi,

I'm using perl back-ticks syntax to run some commands. I would like the output of the command to written to a file and also printed out to stdout. I can accomplish the first by adding a > at the end of my back-ticked string, but I do not know hot to make the output be printed as soon as it is generated. If I do something like

print `command`; 

the output is printed only after command finished executing.

Thanks, Dave

+6  A: 

You cannot do it with the backticks, as they return to the Perl program only when the execution has finished.

So,

print  `command1; command2; command3`;

will wait until command3 finishes to output anything.

You should use a pipe instead of backticks to be able to get output immediately:

open (my $cmds, "-|", "command1; command2; command3");
while (<$cmds>) {
        print;
}
close $cmds;

After you've done this, you then have to see if you want or not buffering (depending on how immediate you want the output to be): Suffering from buffering?

To print and store the output, you can open() a file to write the output to:

open (my $cmds, "-|", "command1; command2; command3");
open (my $outfile, ">", "file.txt");
while (<$cmds>) {
        print;
        print $outfile $_;
}
close $cmds;
close $outfile;
Vinko Vrsalovic
Thank you. Can you please explain/refer me to an explanation of what piping (`"-|"`) actually does?And also, how can I store the command output to a file (in addition to its printing)?
David B
-| says that the output of the command is directed to our program in the three parameters open() call. -| is roughly equivalent to doing "command | our_program". On the other side, |- says that the output of out program will be directed to the command, so it'd be roughly equivalent to "our_program | command". They're not exactly the same, because our_program continues after it's done with command, but that will probably serve to give you an idea.
Vinko Vrsalovic
Thank again. And for the second part of my question - how can I dump the output to a "real" file?
David B
@David B: See edit
Vinko Vrsalovic
Thanks. So how can I tell when the commands are really over? I mean, there are some parts in my program that depend on that the commands are done, so I don't want these parts to execute before they can.
David B
OK, never mind my last question -- "Closing any piped filehandle causes the parent process to wait for the child to finish [...]" (http://perldoc.perl.org/functions/open.html)
David B