6

I need to call some shell commands from perl. Those commands take quite some time to finish so I'd like to see their output while waiting for completion.

The system function does not give me any output until it is completed.

The exec function gives output; however, it exits the perl script from that point, which is not what I wanted.

I am on Windows. Is there a way to accomplish this?

cuteCAT
  • 2,173
  • 4
  • 24
  • 29

1 Answers1

17

Backticks, or the qx command, run a command in a separate process and returns the output:

print `$command`;
print qx($command);

If you wish to see intermediate output, use open to create a handle to the command's output stream and read from it.

open my $cmd_fh, "$command |";   # <---  | at end means to make command 
                                 #         output available to the handle
while (<$cmd_fh>) {
    print "A line of output from the command is: $_";
}
close $cmd_fh;
mob
  • 114,178
  • 18
  • 142
  • 274
  • 1
    @Nathan - Probably, but it's even more important for the external command to have good buffering behavior -- either not buffering its output, or producing output quickly enough that buffering doesn't matter. – mob Dec 14 '10 at 20:35
  • 4
    ++ for backticks AND piped open - The only nitpick I have is the lack of mention of the 3+ args version of the technique, which should be somewhat safer: open my $cmd_fh, '-|', $command; Also, link: http://perldoc.perl.org/perlopentut.html#Pipe-Opens – Hugmeir Dec 14 '10 at 20:54