Question

How can I execute an external command and capture its output in Perl6?

Perl5-style back-ticks don't seem to work:

> my $results = `ls`;
Confused at line 1, near "my $results"

Synopsis 16 documents the run method, but this returns the exit status rather than the output from stdout.

I'm using the Rakudo implementation (rakudo-star-2010.12).

Was it helpful?

Solution

Use qqx or qx instead, e.g.:

> my $results = qqx{ls};

Larry Wall answered an equivalent question on a mailing list:

[...]

: What replaces backtick or qx{} ?

qqx[] or qq:x[] would be the exact equivalent. qx[] or q:x[] would be the same with single-quote semantics. (There are probably no backticks for that purpose since we're reserving ` for user-defined stuff, and because backticks are visually difficult to tell from single quotes in many fonts.)

OTHER TIPS

This can also be done safely (without touching a shell) using run() with the out parameter:

my $proc = run 'ls', q!/tmp/"This" is an ugly name, isn't it?/!, :out;
my $output = $proc.out.slurp-rest;

More details available in the Proc class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top