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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With