在 Perl 中重定向管道的 STDOUT
我觉得好像应该有一个简单的方法来做到这一点,但四处寻找并没有给我很好的线索。我只想open()
到应用程序的管道,向其中写入一些数据,并将子进程的输出发送到调用脚本的STDOUT
。
open(my $foo, '|-', '/path/to/foo');
print $foo 'input'; # Should behave equivalently to "print 'output'"
close($foo);
有没有一种简单的方法可以做到这一点,或者我是否遇到了 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
子进程会自动继承STDOUT。这对我有用:
如果您没有真正立即关闭管道,则问题可能出在另一端:STDOUT 默认情况下是行缓冲的,因此您会立即看到
print "hello world\n"
。默认情况下,通往子进程的管道将是块缓冲的,因此您实际上可能正在等待 Perl 脚本中的数据到达另一个程序:尝试添加
select $f; $| = 1
(或者我认为更现代的方法是$f->autoflush(1)
)The subprocess will inherit STDOUT automatically. This works for me:
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:Try adding
select $f; $| = 1
(or I think the more modern way is$f->autoflush(1)
)