如何在 Perl 中读取和写入管道? [英] How to read to and write from a pipe in Perl?

查看:29
本文介绍了如何在 Perl 中读取和写入管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要修改现有的 Perl 程序.我想通过外部程序通过管道传输一个字符串(可以包含多行)并读取该程序的输出.这个外部程序用于修改字符串.让我们简单地使用 cat 作为过滤程序.我像这样尝试过,但它不起作用.(cat 的输出进入 STDOUT 而不是被 perl 读取.)

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. 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
");
print MESSAGE "Line 1
Line 2
";
my $message = "";
while (<MESSAGE>)
{
    $message .= $_;
}
close(MESSAGE);
print "This is the message: $message
";

我读到 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
";
    $r = <CHLD_OUT>;
    print "Got $r from child
";
}

这篇关于如何在 Perl 中读取和写入管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆