Calling command from Perl, need to see output

cuteCAT picture cuteCAT · Dec 14, 2010 · Viewed 8k times · Source

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?

Answer

mob picture mob · Dec 14, 2010

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;