Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Perl launching process

by pwagyi (Monk)
on Dec 13, 2018 at 10:17 UTC ( [id://1227205] : perlquestion . print w/replies, xml ) Need Help??

pwagyi has asked for the wisdom of the Perl Monks concerning the following question:

Greeting monks! I have been using perl system, backtick for some time to invoke other executables. But then I came across IPC::Cmd run, run_forked, I realize that it's somewhat better in a sense that I can easily access stdout, stderr and also exit code. So the question is when is it appropriate to use each system, backtick, or other modules? Is there best practice?

Replies are listed 'Best First'.
Re: Perl launching process
by haukex (Archbishop) on Dec 13, 2018 at 11:10 UTC
    So the question is when is it appropriate to use each system, backtick, or other modules? Is there best practice?

    See my take on pretty much that exact question here: Calling External Commands More Safely.

    Basically, I would almost always recommend using a module over system and especially backticks, for the reasons I describe there. I usually recommend IPC::System::Simple's systemx and capturex, or if you want control over STDIN and STDERR as well, IPC::Run3.

Re: Perl launching process
by hippo (Bishop) on Dec 13, 2018 at 10:35 UTC

    My Rule of Thumb:

    1. If you don't care about exit codes or output, use system().
    2. If you just want the exit code, use system().
    3. If you just want the output or error or both combined, use backticks.
    4. For anything else, use a module.

      Regarding #3, backtick does not capture stderr by default? Unless shell redirection is used?

        It does not, as a trivial test will confirm.

        $ perl -e 'print "###", `chown foo /`, "###\n"'
Re: Perl launching process
by thanos1983 (Parson) on Dec 13, 2018 at 10:27 UTC
Re: Perl launching process
by Your Mother (Archbishop) on Dec 13, 2018 at 19:40 UTC

    Since no one has brought it up, there is also Capture::Tiny. I use it almost exclusively when not needing to keep pipes around; ongoing reading and writing. Its docs are good so I won't paste a rehashed synopsis here. Though thinking about it, please use strict and declare your variables in the tightest possible scope in your real code. There are a couple schools of thought about doing it in sample code —the synopsis doesn't—and I see both views so won't take a side.

Re: Perl launching process
by karlgoethebier (Abbot) on Dec 14, 2018 at 06:53 UTC
Re: Perl launching process
by jimpudar (Pilgrim) on Dec 13, 2018 at 18:28 UTC

    I've had good luck with Open3.

    πάντων χρημάτων μέτρον έστιν άνθρωπος.