Using perl's `system`

a 夏天 提交于 2019-11-26 06:48:54

问题


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?


回答1:


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.




回答2:


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

More information is in perldoc.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/3477916/using-perls-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!