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

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

问题描述

$ cat test.pl
my $pid = 5892;
my $not = system("top -H -p $pid -n 1 | grep myprocess | wc -l");
print "not = $not
";
$ perl test.pl
11
not = 0
$

我想将结果,即 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:

  • system() :你想执行一个命令并且不想捕获其输出
  • exec:你不想返回到调用 perl 脚本
  • 反引号:您想要捕捉命令的输出
  • open:您想通过管道传输命令 (作为输入或输出)到您的脚本

另见如何从外部命令捕获 STDERR?

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

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