Perl scripts & Open2

I casually use open2 when I want to pipe to/from various programs. However, when I tried to read/write to one of my perl scripts, it failed to work and it is taking me too long to figure it out, so I am asking you guys. I am attaching a very simple example that I expect to work, but it does not. Running test1.pl does nothing, the script hangs at my $r=<READ>. What am I doing wrong?
test1.pl
 
#!/usr/bin/perl
 
use IPC::Open2;
my $pid=open2 (\*READ, \*WRITE, "./test2.pl");
binmode WRITE, ":utf8";
foreach (qw(one two three)) {
    print WRITE "$_\n";
    my $r=<READ>;
    print "+$r+\n"
}
 
test2.pl
 
#!/usr/bin/perl
 
while (<STDIN>) {
    print "*$_*\n";
}

Open in new window

ecuadorAsked:
Who is Participating?
 
ozoConnect With a Mentor Commented:
#!/usr/bin/perl

$|=1;
while (<STDIN>) {
    print "*$_*\n";
}
0
 
ecuadorAuthor Commented:
Simple... thanks!
I wonder why this is not considered worth mentionig in the open2 man pages...
0
 
ozoCommented:
perldoc IPC::Open2
says
       This whole affair is quite dangerous, as you may block forever.  It
       assumes it's going to talk to something like bc, both writing to it and
       reading from it.  This is presumably safe because you "know" that
       commands like bc will read a line at a time and output a line at a
       time.  Programs like sort that read their entire input stream first,
       however, are quite apt to cause deadlock.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.