Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming stdout from a qx subprocess

Tags:

perl

I have a large number of scripts that need to executed. I like to watch the output of said scripts as they go by for debugging purposes.

Typically a print qx/foo/ gathers foo's stdout output until foo is done, then prints it.

I'd like to stream it out, so that I can watch foo's output go by, and capture the output of foo in some scalar.

Ideally:

$cmd = "foo";
$result = stream_and_store($cmd);

I'm reasonably sure there are some sophisticated methods out there, including some nifty CPAN modules.

I'd like to be able to do it in base Perl 5.8.8 (yep, antique, but that's the environment) without adding in other dependencies.

like image 536
Paul Nathan Avatar asked Feb 24 '26 08:02

Paul Nathan


2 Answers

Be careful what you wish for:

$output = `somecmd | tee /dev/tty`;
like image 164
tchrist Avatar answered Feb 26 '26 09:02

tchrist


my $result = '';
open my $proc, '-|', "foo";
while (<$proc>) {
    print $_;
    $result .= $_;
}

This form of the open command launches a process in the background, and makes its output available in the filehandle $proc.

like image 43
mob Avatar answered Feb 26 '26 09:02

mob