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;

利点:

  • 1 つのエラーだけでなく、すべてのエラーをキャッチします。
  • 出力はtar、画面に送信される前に終了するまで保持されません。
  • String::ShellQuote を呼び出さずに、名前にシェルのメタ文字 (スペースなど) を含むアーカイブの問題を解決します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 に答える