How to connect processes via pipe in Perl?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to connect processes via pipe in Perl?



I want to write a Perl script which runs the programs foo and bar and processes stdout of foo and emits it to stdin of bar in a streaming fashion. The Perl script should act like this bash command:


foo


bar


stdout


foo


stdin


bar


bash


$ foo | some-perl-code | bar



I managed to do the first part with the snippet below. I start the program foo and open the pipe to read stdout.


foo


stdout


open( my $pipe_fh, "foo |" );
while ( my $row = <$pipe_fh> )
# do stuff
print $row;



How can I realize the second part? How can I emit $row to the program bar within my Perl script?


$row


bar





Why does this have to be in a Perl scrip? Why can't you use bash directly?
– JGNI
Jul 31 at 10:33




3 Answers
3



Just use another open, but revert the direction of the pipe:


open my $in, '-|', 'foo' or die $!;
open my $out, '|-', 'bar' or die $!;
while ( my $row = <$in> )
# do stuff
print $out $row;



Another option is using IPC::Pipeline to chain the processes together instead of doing it manually.



IPC::Run is also another (somewhat daunting) option. If you end up with complex pipelines, may I also recommend (shameless promotion of own module) IPC::PrettyPipe, which I wrote to help render complex pipelines.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS