如何抑制或重定向到系统命令的变量输出

How to suppress or redirect to the variable output of the system command

我正在尝试执行系统命令,例如

 system('git clone .....' );
    if ($?) {
        croak('Error while cloning git repository');
    }

我在这里检查结果是否成功,但是如何不从系统命令输出错误,例如在我的情况下,我可以得到类似

的东西
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

来自执行的命令。
我需要将此错误放入变量中并抑制它(不要将其打印到终端)
然后检查此错误消息。
或者至少只是抑制它。
我需要通过以下方式测试这样的子程序

dies_ok { MyModule::sub_uses_system_command() } 'Died :(';

有可能得到这样的结果吗?
提前致谢。

而不是 system,使用 qx 来捕获命令的输出。看起来您还想捕获 stderr,因此使用标准 2>&1 将 stderr 复制到 stdout。

 $var = qx( git clone ... 2>&1 )

system only returns the exit status of the program that was executed, if you want to get the standard output you can use qx/command/ 或反引号执行命令:

my $result = `git clone [...] 2>&1`

您应该注意,执行命令的 qx/command/ 和反引号形式仅 returns STDOUT,因此如果您想捕获 STDERR,您需要在命令中将 STDERR 重定向到 STDOUT。

如果您需要执行多个输出到 STDERR/STDOUT 的测试,您可以在一个块中重定向它们,然后 运行 在其中重定向所有这些测试。这是一个基本示例。

sub use_system {
    system("asdfasdf asdfasdf");
    croak('this error') if $?;
}

{
    open my $stderr, '>', 'temp.fil' or die $!;
    local *STDERR = $stderr;

    dies_ok { use_system() } 'Died :(';

    # or even

    eval { use_system(); };

    like ($@, qr/this error/, "function failed with 'this error'");
}

warn "STDERR back to normal\n";