tags:

views:

898

answers:

2

If I have this perl app:

print `someshellscript.sh`;

that prints bunch of stuff and takes a long time to complete, how can I print that output in the middle of execution of the shell script?

Looks like Perl will only print the someshellscript.sh result when it completes, is there a way to make output flush in the middle of execution?

+1  A: 

The problem here is that escaping with backticks stores your script to a string, which you then print. For this reason, there would be no way to "flush" with print.

Using the system() command should print output continuously, but you won't be able to capture the output:

system "someshellscript.sh";
Stefan Kendall
+1. EDIT: I added a quick demonstration of system(), and deleted my own answer which was otherwise redundant.
j_random_hacker
+11  A: 

What you probably want to do is something like this:

open(F, "someshellscript.sh|");
while (<F>) {
    print;
}
close(F);

This runs someshellscript.sh and opens a pipe that reads its output. The while loop reads each line of output generated by the script and prints it. See the open documentation page for more information.

Greg Hewgill
The only thing I would add is that it's usually better to use a lexical filehandle: open my $fh, "someshellscript.sh|" or die $!;
friedo
why is that better?
Nathan Fellman
@Nathan: (1) You can't accidentally clobber an existing filehandle in a containing scope; (2) A lexical filehandle will be automatically closed when all references to the filehandle disappear (usually on scope exit).
j_random_hacker