如何将系统命令的结果存储在Perl变量中? [英] How can I store the result of a system command in a Perl variable?

查看:167
本文介绍了如何将系统命令的结果存储在Perl变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ 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
$

我想捕获结果ie 11 到一个变量。我该如何做?

I want to capture the result i.e. 11 into a variable. How can I do that?

推荐答案

Perlfaq8

您混淆了 system()反引号(``)。 system()运行命令并返回退出状态信息(作为16位值:低7位是进程死亡的信号,如果有的话,高8位是实际退出值)。反引号(``)运行一个命令,并返回它发送到STDOUT。

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`;

有很多方法可以从Perl执行外部命令。最常见的含义是:

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


  • exec :您不想返回到
    调用perl脚本

  • 反引号 :您要捕获
    命令的输出

  • 打开 / strong>您希望将命令(作为
    输入或输出)转换为您的脚本

  • 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

=http://perldoc.perl.org/perlfaq8.html#How-can-I-capture-STDERR-from-an-external-command%3f>如何从外部命令捕获STDERR?

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

这篇关于如何将系统命令的结果存储在Perl变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆