从 Perl 中的命令获取返回码和输出 [英] Get return code and output from command in Perl

查看:83
本文介绍了从 Perl 中的命令获取返回码和输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个实用程序,该实用程序将遍历如下所示的文件:

I'm trying to write a utility that will go through a file that would look like this:

# Directory | file name | action | # of days without modification to the file for the command to take action
/work/test/|a*|delete|1
/work/test/|b*|compress|0
/work/test/|c*|compress|1

我的脚本将通过文件来决定,例如,/work/test/下是否有以 'a' 开头的文件在过去 1 天内未被修改,如果是,它将删除他们.

My script will go through the file deciding if, for example, there are files under /work/test/ that start with 'a' that haven't been modified in the last 1 days, and if so, it would delete them.

为此,我使用 find 命令.示例:

For this, I use the find command. Example:

my $command = "find " . $values[0] . $values[1] . " -mtime +" . $values[3] . " -delete ;\n";
system ($command);

但是,我被要求检索每个步骤的返回代码,以验证每个步骤是否正常工作.

But, I've been asked to retrieve the return code for each step to verify that the every step worked fine.

现在,我知道 system() 返回返回码,反引号返回输出.但是,我怎样才能得到两者呢?

Now, I know that system() returns the return code, and the backticks return the output. But, how can I get both?

推荐答案

运行反引号后,返回代码在 $?.

After backticks are run, the return code is available in $?.

$?

由最后一个管道关闭、反引号 (``) 命令、成功调用 wait() 或 waitpid() 或从 system() 运算符返回的状态.这只是由传统的 Unix wait() 系统调用返回的 16 位状态字(或者看起来像它).

The status returned by the last pipe close, backtick (``) command, successful call to wait() or waitpid(), or from the system() operator. This is just the 16-bit status word returned by the traditional Unix wait() system call (or else is made up to look like it).

$output = `$some_command`;
print "Output of $some_command was '$output'.\n";
print "Exit code of $some_command was $?\n";

这篇关于从 Perl 中的命令获取返回码和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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