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

前端 未结 5 790
醉梦人生
醉梦人生 2020-11-29 21:05
$ cat test.pl
my $pid = 5892;
my $not = system(\"top -H -p $pid -n 1 | grep myprocess | wc -l\");
print \"not = $not\\n\";
$ perl test.pl
11
not = 0
$
5条回答
  •  北海茫月
    2020-11-29 21:35

    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?

提交回复
热议问题