如何在Perl中读取和写入管道? [英] How to read to and write from a pipe in Perl?
问题描述
我是Perl菜鸟,所以请原谅这个基本问题.我需要修改现有的Perl程序.我想通过外部程序通过管道传递一个字符串(其中可以包含多行),并读取该程序的输出.因此,此外部程序用于修改字符串.让我们简单地使用cat
作为过滤程序.我这样尝试过,但是没有用. (cat
的输出转到stdout,而不是被perl
读取.)
I'm a Perl noob, so please excuse this basic question. I need to modify an existing Perl program. I want to pipe a string (Which can contain multiple lines) through an external program and read the output from this program. So this external program is used to modify the string. Let's simply use cat
as a filter program. I tried it like this but it doesn't work. (Output of cat
goes to stdout instead of being read by perl
.)
#!/usr/bin/perl
open(MESSAGE, "| cat |") or die("cat failed\n");
print MESSAGE "Line 1\nLine 2\n";
my $message = "";
while (<MESSAGE>)
{
$message .= $_;
}
close(MESSAGE);
print "This is the message: $message\n";
我读到Perl不支持此操作,因为它可能最终陷入死锁,并且我可以理解.但是我该怎么办呢?
I've read that this isn't supported by Perl because it may end up in a deadlock and I can understand it. But how do I do it then?
推荐答案
您可以使用 IPC :: Open3 实现与孩子的双向通信.
You can use IPC::Open3 to achieve bi-directional communication with child.
use strict;
use IPC::Open3;
my $pid = open3(\*CHLD_IN, \*CHLD_OUT, \*CHLD_ERR, 'cat')
or die "open3() failed $!";
my $r;
for(my $i=1;$i<10;$i++) {
print CHLD_IN "$i\n";
$r = <CHLD_OUT>;
print "Got $r from child\n";
}
这篇关于如何在Perl中读取和写入管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!