Search code examples
perlsystemexecution

Using perl's `system`


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?


Solution

  • 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.