Search code examples
perlbackticks

How can I read the error output of external commands in Perl?


As part of a larger Perl program, I am checking the outputs of diff commands of input files in a folder against reference files, where a blank output (a match) is a passing result, and any output from diff is a fail result.

The issue is, if the target folder is short on the number of expected files, the exception diff throws doesn't come as output, creating false passes.

Output Example:

diff: /testfolder/Test-02/test-output.2: No such file or directory

Test-01: PASS

Test-02: PASS

The code goes as such:

$command = "(diff call on 2 files)";
my @output = `$command`;
print "Test-02: ";
$toPrint = "PASS";
foreach my $x (@output) {
    if ($x =~ /./) {
        $toPrint = "FAIL";
    }
}

This is a quick hackery job to fail if there is any output from the diff call. Is there a way to check for exceptions thrown by the command called in the backticks?


Solution

  • Programs themselves can't throw "exceptions", but they can return nonzero error codes. You can check the error code of a program run with backticks or system() in Perl using $?:

    $toPrint = "FAIL" if $?;
    

    (Add this line before the loop that tests @output.)