views:

88

answers:

4

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?

+5  A: 
my @args = qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
system(@args) == 0 or die "system @args failed: $?";

More information is in perldoc.

eugene y
A: 

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.

Cfreak
*Speed* is not the issue with the string versus array as arguments to system: http://perldoc.perl.org/functions/system.html
Sinan Ünür
Downvote: security takes precedence over speed anytime.
daxim
+1  A: 
my @args = ( "command", "--arg1=arg1", "--arg2=arg2", "-arg3", "-arg4" );
system(@args);
gangabass
Downvote for no error checking.
daxim
+6  A: 

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.

daxim
To do system "properly" you must decode `$?`? I don't think so.
ysth
I'm bewildered that a man of your expertise doesn't know that indeed it needs decoding.
daxim
Well, you might simply not care about anything beyond "zero" and "not zero".
hobbs