gpt4 book ai didi

perl - 如何在Perl中读写管道?

转载 作者:行者123 更新时间:2023-12-03 14:35:27 27 4
gpt4 key购买 nike

我需要修改现有的Perl程序。我想通过外部程序通过管道传递一个字符串(可以包含多行),并读取该程序的输出。该外部程序用于修改字符串。让我们简单地使用cat作为过滤程序。我这样尝试过,但是没有用。 (cat的输出进入STDOUT,而不是被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不支持此功能,因为它可能最终陷入僵局,我可以理解。但是我该怎么办呢?

最佳答案

您可以使用IPC::Open3与 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 - 如何在Perl中读写管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10765311/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com