Redirecting STDOUT of a pipe in Perl

邮差的信 提交于 2020-01-04 06:14:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!