0

I have 2 perl scripts A and B. inside B.pl I want to check if there are syntax errors in A.pl

I'm using $result =`perl -c A.pl`; but I can't get the output in $result. I need a perl command to do that. can you help?

2
  • 2
    For capturing output of an external command, see the qx operator in perlop. For more advanced captures see also Getting STDOUT, STDERR, and response code from external *nix command in perl. Commented Jul 3, 2016 at 9:56
  • This is a textbook case of where SO fails lamely. I see a banner on top of this question that it already has answers. 2 actually. And as a result it is now closed. But both allegded answers are about how to capture stdout/stderr of a Perl system() command. Of course this question asks something completely different and yet 6 years later not even those SOers who so eagerly hijack and edit questions, picking, at best, minor spelling mistakes and syntactical faux-pas, have not corrected it. Perhaps they have not noticed it even. The hallmarks of a Bureaucracy. Commented Nov 9, 2022 at 16:06

2 Answers 2

1

You can capture the output and check for the string syntax OK

A.pl

#!/usr/bin/env perl

use warnings;
use strict;

main();
exit 0;

sub main {
    my ($stuff) = @_;
    # Syntax Error
    print $stufff;

    # Runtime Error
    pint $stuff;

    # Runtime Error
    print $stuff->foo();
}

B.pl

#!/usr/bin/env perl

use warnings;
use strict;
use Test::More;

for my $file ( qw( A.pl B.pl ) ) {
    # 2>&1 means redirect STDERR to STDOUT so we can capture it
    chomp(my ($result) = qx( /usr/bin/env perl -cw $file 2>&1 ));
    ok( $result =~ m|syntax OK|m, "$file compiles OK" )
        or diag( "$file failed to compile : $result" );
}

done_testing();

Output

perl B.pl
not ok 1 - A.pl compiles OK
#   Failed test 'A.pl compiles OK'
#   at B.pl line 8.
# A.pl failed to compile : Global symbol "$stufff" requires explicit package name at A.pl line 12.
ok 2 - B.pl compiles OK
1..2
# Looks like you failed 1 test of 2.
Sign up to request clarification or add additional context in comments.

Comments

-1
my $res = system("perl -c test.pl");
unless ($res) {
    print "OK\n";
} else {
    print "Syntax error!\n";
}

1 Comment

Author said that it doesn't work. And backtics captures STDOUT, not STDERR perl reports errors. Would be nice to check your code before posting it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.