如何将系统命令的结果存储在 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
$
我想将结果(即 11
)捕获到变量中。我怎样才能做到这一点?
$ 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
$
I want to capture the result i.e. 11
into a variable. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
来自 Perlfaq8:
您混淆了 system() 和 反引号 (``)。 system() 运行命令并返回退出状态信息(作为 16 位值:低 7 位是进程死亡的信号(如果有),高 8 位是实际退出值)。反引号 (``) 运行命令并将其发送到 STDOUT 的内容返回。
有多种方法可以从 Perl 执行外部命令。最常见的含义是:
调用perl脚本
命令的输出
输入或输出)到您的脚本
另请参阅 如何从外部命令捕获 STDERR?
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.
There are many ways to execute external commands from Perl. The most commons with their meanings are:
calling perl script
output of the command
input or output) to your script
Also see How can I capture STDERR from an external command?
最简单的方法是使用 Perl 中的
``
功能。这将执行里面的内容并将打印的内容返回到标准输出:这应该可以做到。
The easiest way is to use the
``
feature in Perl. This will execute what is inside and return what was printed to stdout:This should do it.
尝试使用 qx{command} 而不是反引号。对我来说,它更好一点,因为:你可以用它执行 SQL,而不用担心转义引号之类的问题。根据编辑器和屏幕的不同,我的老眼睛往往会错过微小的反勾号,并且它不应该出现像使用尖括号与通配符那样的过载问题。
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.使用
backtick
或qx
有帮助,感谢大家的回答。但是,我发现如果您使用backtick
或qx
,输出会包含尾随换行符,我需要将其删除。所以我使用了 chomp。更多信息请点击这里:
http://irouble.blogspot.in/2011/04/perl-chomp -反引号.html
Using
backtick
orqx
helps, thanks everybody for the answers. However, I found that if you usebacktick
orqx
, the output contains trailing newline and I need to remove that. So I usedchomp
.More information here:
http://irouble.blogspot.in/2011/04/perl-chomp-backticks.html
对系统命令使用反引号,这有助于将其结果存储到 Perl 变量中。
Use backticks for system commands, which helps to store their results into Perl variables.
也用于例如。您可以使用 IPC::Run:
Also for eg. you can use IPC::Run: