Using perl `system`

I would like to execute some command (e.g. command ) using perl system() . Suppose command is executed from the shell as follows:

 command --arg1=arg1 --arg2=arg2 -arg3 -arg4 

How to use system() to run command with these arguments?

+3
perl system execution
source share
4 answers

Recommendations: 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: an inscription appears.

eugene y answer contains a link to the documentation in the system. There we can see a piece of code that needs to be included every time to make the system correct. eugene y answer shows, but part of it.

Whenever we are in this situation, we collect duplicate code in a module. I draw parallels with the correct exception handling using Try::Tiny , however IPC::System::Simple , since the system done correctly, did not see this quick adoption from the community. It seems to need to be repeated more often.

So use autodie ! Use IPC::System::Simple ! Save boredom, be sure to use proven code.

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

Further information is available at perldoc .

+5
source share

Like everything in Perl, there is more than one way to do this :)

Best way: pass arguments as a list:

 system("command", "--arg1=arg1","--arg2=arg2","-arg3","-arg4"); 

Although sometimes programs do not look good with this version (especially if they expect a call from the shell). Perl will invoke the command from the shell if you make it as a single line.

 system("command --arg1=arg1 --arg2=arg2 -arg3 -arg4"); 

But this form is slower.

+1
source share
 my @args = ( "command", "--arg1=arg1", "--arg2=arg2", "-arg3", "-arg4" ); system(@args); 
+1
source share

All Articles