1

我正在尝试测试反引号输出字符串(它是字符串,对吗??)是否包含子字符串。

my $failedCoutner = 0;
my $tarOutput = `tar -tvzf $tgzFile`;
print "$tarOutput\n";

my $subStr = "Cannot open: No such file or directory";
if (index($tarOutput, $subStr) != -1)
{
    push(@failedFiles, $tgzFile);
    $failedCounter++;
    print "Number of Failed Files: $failedCounter\n\n\n";
}
print "Number of Failed Files: $failedCounter\n\n\n";

但这行不通。它从不进入 if 语句。

反引号输出:

tar (child): /backup/Arcsight/EDSSIM004: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now

Number of Failed Files: 0

显然子字符串在第一行。为什么不认这个??

4

2 回答 2

1

tar与大多数程序一样,将错误消息写入 STDERR。这就是 STDERR 的目的。

反引号仅捕获 STDOUT。

您可以将tar的 STDERR 重定向到其 STDOUT,但为什么不检查其退出代码。

system('tar', '-tvzf', $tgzFile);
die "Can't launch tar: $!\n" if $? == -1;
die "tar killed by signal ".($? & 0x7F) if $? & 0x7F;
die "tar exited with error ".($? >> 8) if $? >> 8;

优点:

  • 捕获所有错误,而不仅仅是一个。
  • tar在发送到屏幕之前,输出不会一直保留到完成。
  • 它解决了名称中包含 shell 元字符(例如空格)的存档问题,而无需调用 String::ShellQuote's shell_quote
于 2013-05-22T06:03:13.677 回答
0

检查反引号是否产生错误$?

use warnings;
use strict;

my $tarOutput = `tar -tvzf doesnt_exist.tar.gz`;
if ($?) {
    print "ERROR ... ERROR ... ERROR\n";
}
else {
    # do something else
}

__END__

tar (child): doesnt_exist.tar.gz: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
ERROR ... ERROR ... ERROR
于 2013-05-21T21:03:19.403 回答