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

  • A+
Category:Languages

system, exec, open '|-', open2, etc. all allow me to specify the command to run as a list of arguments that will be passed directly to execvp instead of run through a shell.

Even if perl is smart enough to run it directly if it looks like a "simple" command, that saves me the trouble of correctly shell-escaping the arguments with all the nasty pitfalls that it entails.

Example:

open my $out, '|-', $prog, @args; system $prog, @args; exec $prog, @args; 

instead of

open my $out, "|$prog @args"; system "$prog @args"; exec "$prog @args"; 

Is there such an equivalent for the qx// operator? Or do you have to always do it by hand eg.

sub slurpcmd {    open my $h, '-|', @_ or die "open $_[0]|: $!";    local $/ unless wantarray;    <$h> } 

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: