Demi Demi - 2 months ago 8
Perl Question

In Perl, how do I pipe the output of one command to the input of another?

In Perl, how can pipe the output of one command to the input of another?

I want to do it the way the shell does it, but without using the shell.

Answer

This is easy using IPC::Run.

run \@cmd1, '|', \@cmd2;

For example,

prog0:

#!/usr/bin/perl
use IPC::Run qw( run );
print("The parent's PID is $$\n");
run([ 'prog1' ], '|', [ 'prog2' ]);

prog1:

#!/usr/bin/perl
print("cmd1's parent's PID is ".getppid()."\n");

prog2:

#!/usr/bin/perl
while (<>) {
   chomp;
   print("Got <<$_>>\n");
}
print("cmd2's parent's PID is ".getppid()."\n");

Output from prog0:

The parent's PID is 6619
Got <<cmd1's parent's PID is 6619>>
cmd2's parent's PID is 6619
Comments