К сожалению, вы не можете передавать двойные каналы в open
, как хотелось бы, и загрузка IPC :: Open2 не исправляет это.Вы должны использовать функцию open2
, экспортированную с помощью IPC :: Open2.
use strict;
use warnings;
use IPC::Open2;
use IO::Handle; # so we can call methods on filehandles
my $command = 'cat';
open2( my $out, my $in, $command ) or die "Can't open $command: $!";
# Set both filehandles to print immediately and not wait for a newline.
# Just a good idea to prevent hanging.
$out->autoflush(1);
$in->autoflush(1);
# Send lines to the command
print $in "Something\n";
print $in "Something else\n";
# Close input to the command so it knows nothing more is coming.
# If you don't do this, you risk hanging reading the output.
# The command thinks there could be more input and will not
# send an end-of-file.
close $in;
# Read all the output
print <$out>;
# Close the output so the command process shuts down
close $out;
Этот шаблон работает, если все, что вам нужно сделать, это отправить команде несколько строк и затем прочитать вывод один раз.Если вам нужно быть интерактивным, вашей программе очень просто повиснуть в ожидании вывода, который никогда не поступит.Для интерактивной работы я бы предложил IPC :: Run .Он довольно силен, но он охватывает практически все, что вы можете захотеть сделать с помощью внешнего процесса.