How do you capture stderr, stdout, and the exit code all at once, in Perl?

后端 未结 6 2205
情深已故
情深已故 2020-11-27 03:19

Is it possible to run an external process from Perl, capture its stderr, stdout AND the process exit code?

I seem to be able to do combinations of these, e.g. use ba

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 03:54

    There are three basic ways of running external commands:

    system $cmd;        # using system()
    $output = `$cmd`;       # using backticks (``)
    open (PIPE, "cmd |");   # using open()
    

    With system(), both STDOUT and STDERR will go the same place as the script's STDOUT and STDERR, unless the system() command redirects them. Backticks and open() read only the STDOUT of your command.

    You could also call something like the following with open to redirect both STDOUT and STDERR.

    open(PIPE, "cmd 2>&1 |");
    

    The return code is always stored in $? as noted by @Michael Carman.

提交回复
热议问题