简体   繁体   中英

Redirecting STDOUT of a pipe in Perl

I feel as though there should be a simple way to do this, but searching around gives me no good leads. I just want to open() a pipe to an application, write some data to it, and have the output of the subprocess sent to the STDOUT of the calling script.

open(my $foo, '|-', '/path/to/foo');
print $foo 'input'; # Should behave equivalently to "print 'output'"
close($foo);

Is there a simple way to do this, or have I hit upon one of the many "can't get there from here" moments in Perl?

The subprocess will inherit STDOUT automatically. This works for me:

open(my $f, "|-", "cat");
print $f "hi\n";

If you are not really closing the pipe immediately the problem might be on the other end: STDOUT is line-buffered by default, so you see print "hello world\\n" immediately. The pipe to your subprocess will be block-buffered by default, so you may actually be waiting for the data from your perl script to reach the other program:

open(my $f, "|-", "cat");
print $f "hi\n";
sleep(10);
close($f); # or exit
# now output appears

Try adding select $f; $| = 1 select $f; $| = 1 select $f; $| = 1 (or I think the more modern way is $f->autoflush(1) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM