-->

How to pipe a string to process' STDIN?

2019-07-06 11:22发布

问题:

I have a command that expects input from a pipe. For example, consider the famous cat command:

$ echo Hello | cat
Hello

Suppose I have a string in a Perl 6 program that I want to pipe to the command:

use v6;

my $input = 'Hello'; # This is the string I want to pipe to the command.
my $proc  = run 'cat', :in($input);

This does not work (I get no output). I can work around the problem by invoking bash and echo:

my $proc  = run 'bash', '-c', "echo $input | cat";

But is there a way I can do this without running bash and echo?

In Perl5, I could simply do my $pid = open my $fh, '|-', 'cat'; and then print $fh $str.

回答1:

Piping several commands is easy too. To achieve the equivalent of the pipe echo "Hello, world" | cat -n in Perl 6, and capture the output from the second command, you can do

my $p1 = run 'echo', 'Hello, world', :out;
my $p2 = run 'cat', '-n', :in($p1.out), :out;
say $p2.out.get;

You can also feed the :in pipe directly from your program, by setting it to True, which will make the pipe available via .in method on the Proc:

my $p = run "cat", "-n", :in, :out;
$p.in.say: "Hello,\nworld!";
$p.in.close;
say $p.out.slurp: :close;
# OUTPUT: «1  Hello,␤ 
#          2  world!␤» 

Straight from the docs, btw



标签: pipe perl6