How can I run an external command and capture its output in Perl?

后端 未结 4 1900
南旧
南旧 2020-12-06 00:34

I\'m new to Perl and want to know of a way to run an external command (call it prg) in the following scenarios:

  1. Run prg, get its
4条回答
  •  天涯浪人
    2020-12-06 00:43

    In most cases you can use the qx// operator (or backticks). It interpolates strings and executes them with the shell, so you can use redirections.

    • To capture a command's STDOUT (STDERR is unaffected):

      $output = `cmd`;
      
    • To capture a command's STDERR and STDOUT together:

      $output = `cmd 2>&1`;
      
    • To capture a command's STDERR but discard its STDOUT (ordering is important here):

      $output = `cmd 2>&1 1>/dev/null`;
      
    • To exchange a command's STDOUT and STDERR in order to capture the STDERR but leave its STDOUT to come out the old STDERR:

      $output = `cmd 3>&1 1>&2 2>&3 3>&-`;
      
    • To read both a command's STDOUT and its STDERR separately, it's easiest to redirect them separately to files, and then read from those files when the program is done:

      system("program args 1>program.stdout 2>program.stderr");
      

提交回复
热议问题