Perl索引功能不起作用?

时间:2013-05-21 20:43:01

标签: perl indexing backticks

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

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

显然,子串位于第一行。为什么不认识这个?

2 个答案:

答案 0 :(得分: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的shell_quote

答案 1 :(得分:0)

检查$?是否backticks产生了错误:

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