问题
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?
回答1:
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
(or I think the more modern way is $f->autoflush(1)
)
来源:https://stackoverflow.com/questions/4114668/redirecting-stdout-of-a-pipe-in-perl