捕获 Perl 的“system()"的输出 [英] Capture the output of Perl's 'system()'

查看:71
本文介绍了捕获 Perl 的“system()"的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Perl 中使用 system() 运行 shell 命令.例如,

I need to run a shell command with system() in Perl. For example,

system('ls')

系统调用将打印到 STDOUT,但我想捕获输出转换成一个变量,以便我可以用我的 Perl 代码做未来的处理.

The system call will print to STDOUT, but I want to capture the output into a variable so that I can do future processing with my Perl code.

推荐答案

这就是反引号的用途.来自 perldoc perlfaq8:

That's what backticks are for. From perldoc perlfaq8:

为什么我无法使用 system() 获得命令的输出?

Why can't I get the output of a command with system()?

您混淆了 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.

my $exit_status   = system("mail-users");
my $output_string = `ls`;

有关详细信息,请参阅 perldoc perlop.

See perldoc perlop for more details.

这篇关于捕获 Perl 的“system()"的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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