Paul Nathan
Paul Nathan

Reputation: 40319

Streaming stdout from a qx subprocess

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.

Upvotes: 3

Views: 958

Answers (2)

mob
mob

Reputation: 118665

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.

Upvotes: 3

tchrist
tchrist

Reputation: 80433

Be careful what you wish for:

$output = `somecmd | tee /dev/tty`;

Upvotes: 3

Related Questions