How can I store the result of a system command in a Perl variable?

From Perlfaq8:

You’re confusing the purpose of system() and backticks (“). system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (“) run a command and return what it sent to STDOUT.

$exit_status   = system("mail-users");
$output_string = `ls`;

There are many ways to execute external commands from Perl. The most commons with their meanings are:

  • system() : you want to execute a command and don’t want to capture its output
  • exec: you don’t want to return to the
    calling perl script
  • backticks : you want to capture the
    output of the command
  • open: you want to pipe the command (as
    input or output) to your script

Also see How can I capture STDERR from an external command?

Leave a Comment

tech