在Perl中重定向管道的STDOUT [英] Redirecting STDOUT of a pipe in Perl
问题描述
我觉得应该有一个简单的方法来做到这一点,但是四处搜寻并没有给我带来好的线索.我只想open()
到应用程序的管道,向其中写入一些数据,然后将子进程的输出发送到调用脚本的STDOUT
.
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);
是否有一种简单的方法可以做到这一点,或者在Perl中遇到了许多无法从这里到达那里"的事件之一?
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?
推荐答案
子进程将自动继承STDOUT.这对我有用:
The subprocess will inherit STDOUT automatically. This works for me:
open(my $f, "|-", "cat");
print $f "hi\n";
如果您没有真正立即关闭管道,则问题可能出在另一端:默认情况下,STDOUT是行缓冲的,因此您会立即看到print "hello world\n"
.默认情况下,子进程的管道将使用块缓冲,因此您实际上可能正在等待perl脚本中的数据到达其他程序:
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
尝试添加select $f; $| = 1
(或者我认为更现代的方式是$f->autoflush(1)
)
Try adding select $f; $| = 1
(or I think the more modern way is $f->autoflush(1)
)
这篇关于在Perl中重定向管道的STDOUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!