develooper Front page | perl.perl6.users | Postings from August 2017

Running external CLI tool and capturing output

Thread Next
Gabor Szabo
August 10, 2017 14:57
Running external CLI tool and capturing output
Message ID:
The documentation has a nice example showing how to run an external
program and how to get its output or even its standard error.

However it looks a lot more complex than the plain backtick Perl 5 has
and more complex than the capture function of Capture::Tiny.
IMHO it is way too much code.

I wrote a simple function wrapping it:

sub capture(*@args) {
    my $p = run @args, :out, :err;
    my $output = $p.out.slurp: :close;
    my $error  = $p.err.slurp: :close;
    my $exit   = $p.exitcode;

    return {
        out  => $output,
        err  => $error,
        exit => $exit;

It can be used as:

my $res = capture($*EXECUTABLE, 'bin/create_db.pl6');
say $res<out>;

or even

say capture($*EXECUTABLE, 'bin/create_db.pl6')<out>;

I wonder if I have just invented something that already exist in
Rakudo or if it is not there, then wouldn't it be a good idea to add
such a simple way to run external commands?

ps. Backtick actually expected a single string and not a list of
parameters and supporting that mode, even if it is less secure, might
be also a good idea.

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About