2

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

daxim
  • 39,270
  • 4
  • 65
  • 132
David B
  • 29,258
  • 50
  • 133
  • 186

1 Answers1

8

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
  • 330,807
  • 53
  • 334
  • 373
  • 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 Jul 31 '10 at 11:53
  • -| 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 Jul 31 '10 at 12:05
  • Thank again. And for the second part of my question - how can I dump the output to a "real" file? – David B Jul 31 '10 at 12:08
  • 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 Jul 31 '10 at 13:04
  • 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 Jul 31 '10 at 13:43