문제

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

도움이 되었습니까?

해결책

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top