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

前端 未结 5 778
醉梦人生
醉梦人生 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?

    0 讨论(0)
  • 2020-11-29 21:36

    Use backtick for system commands which helps to store their result into Perl variable.

    my $pid = 5892; my $not = ``top -H -p $pid -n 1 | grep myprocess | wc -l`; print "not = $not\n";

    0 讨论(0)
  • 2020-11-29 21:46

    Try using qx{command} rather than backticks. To me, it's a bit better because: you can do SQL with it and not worry about escaping quotes and such. Depending on the editor and screen, my old eyes tend to miss the tiny back ticks, and it shouldn't ever have an issue with being overloaded like using angle brackets versus glob.

    0 讨论(0)
  • 2020-11-29 21:54

    Using backtick or qx helps, thanks everybody for the answers. However, I found that if you use backtick or qx, the output contains trailing newline and I need to remove that. So I used chomp.

    chomp($host = `hostname`);
    chomp($domain = `domainname`);
    $fqdn = $host.".".$domain;
    

    More information here: http://irouble.blogspot.in/2011/04/perl-chomp-backticks.html

    0 讨论(0)
  • 2020-11-29 22:01

    The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout:

     my $pid = 5892;
     my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`;
     print "not = $var\n";
    

    This should do it.

    0 讨论(0)
提交回复
热议问题