use perl's qx{} / `...` operator with a list of arguments

A list form of the qx operator is provided by the module IPC::System::Simple as the function capturex (additionally like the other functions in that module, it will throw an exception if there is an execution error or non-zero response code, which you can tweak). Alternatively, you can use Capture::Tiny to wrap a core system call and provide the same behavior, but it also has other functions that can wrap STDERR together or separately from STDOUT.

use strict;
use warnings;
use IPC::System::Simple 'capturex';
my $output = capturex $prog, @args;

use Capture::Tiny 'capture_stdout';
my ($output, $exit) = capture_stdout { system $prog, @args };
# standard system() error checking required here

In core the pipe open is for the most part the only option, aside from IPC::Open3 which is similarly complex but allows directing STDERR as well.


Here are a few simple options.

  • String::ShellQuote + qx:

    use String::ShellQuote qw( shell_quote );
    my $cmd = shell_quote(@cmd);
    my $output = `$cmd`;
    
  • IPC::System::Simple:

    use IPC::System::Simple qw( capturex );
    my $output = capturex(@cmd)
    
  • IPC::Run3:

    use IPC::Run3 qw( run3 );
    run3(\@cmd, \undef, \my $output);
    
  • IPC::Run:

    use IPC::Run qw( run );
    run(\@cmd, \undef, \my $output);
    

The first solution involves a shell, but none of the others.

Tags:

Perl

Backticks

Qx