简体   繁体   English

在Perl中重定向管道的STDOUT

[英]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()到应用程序的管道,向其中写入一些数据,然后将子进程的输出发送到调用脚本的STDOUT

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? 有没有简单的方法可以做到这一点,或者我遇到了Perl众多“无法从这里到达那里”的时刻之一?

The subprocess will inherit STDOUT automatically. 子进程将自动继承STDOUT。 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. 如果不是真的立即关闭管道,则问题可能出在另一端:默认情况下,STDOUT是行缓冲的,因此您会立即看到print "hello world\\n" 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: 默认情况下,子进程的管道将使用块缓冲,因此您实际上可能正在等待perl脚本中的数据到达其他程序:

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 select $f; $| = 1 (or I think the more modern way is $f->autoflush(1) ) select $f; $| = 1 (或者我认为更现代的方法是$f->autoflush(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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