I would like to run some command (e.g. command
) using perl's system()
. Suppose command
is run from the shell like this:
command --arg1=arg1 --arg2=arg2 -arg3 -arg4
How do I use system()
to run command
with these arguments?
I would like to run some command (e.g. command
) using perl's system()
. Suppose command
is run from the shell like this:
command --arg1=arg1 --arg2=arg2 -arg3 -arg4
How do I use system()
to run command
with these arguments?
As with everything in Perl, there's more than one way to do it :)
The best way, Pass the arguments as a list:
system("command", "--arg1=arg1","--arg2=arg2","-arg3","-arg4");
Though sometimes programs don't seem to play nice with that version (especially if they expect to be invoked from a shell). Perl will invoke the command from the shell if you do it as a single string.
system("command --arg1=arg1 --arg2=arg2 -arg3 -arg4");
But that form is slower.
my @args = ( "command", "--arg1=arg1", "--arg2=arg2", "-arg3", "-arg4" );
system(@args);
Best practices: avoid the shell, use automatic error handling - IPC::System::Simple
.
require IPC::System::Simple;
use autodie qw(:all);
system qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
use IPC::System::Simple qw(runx);
runx [0], qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
# ↑ list of allowed EXIT_VALs, see documentation
Edit: a rant follows.
eugene y's answer includes a link to the documentation to system. There we can see a homungous piece of code that needs to be included everytime to do system
properly. eugene y's answer shows but a part of it.
Whenever we are in such a situation, we bundle up the repeated code in a module. I draw parallels to proper no-frills exception handling with Try::Tiny
, however IPC::System::Simple
as system
done right did not see this quick adoption from the community. It seems it needs to be repeated more often.
So, use autodie
! Use IPC::System::Simple
! Save yourself the tedium, be assured that you use tested code.