Using perl's `system`

前端 未结 4 2165
逝去的感伤
逝去的感伤 2020-11-27 08:10

I would like to run some command (e.g. command) using perl\'s system(). Suppose command is run from the shell like this:



        
相关标签:
4条回答
  • 2020-11-27 08:41

    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.

    0 讨论(0)
  • 2020-11-27 08:46
    my @args = qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
    system(@args) == 0 or die "system @args failed: $?";
    

    More information is in perldoc.

    0 讨论(0)
  • 2020-11-27 09:03
    my @args = ( "command", "--arg1=arg1", "--arg2=arg2", "-arg3", "-arg4" );
    system(@args);
    
    0 讨论(0)
  • 2020-11-27 09:05

    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.

    0 讨论(0)
提交回复
热议问题