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?

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 2
    For capturing output of an external command, see the [`qx`](http://perldoc.perl.org/perlop.html#Quote-Like-Operators) operator in [`perlop`](http://perldoc.perl.org/perlop.html). For more advanced captures see also [Getting STDOUT, STDERR, and response code from external *nix command in perl](http://stackoverflow.com/q/8733131/2173773). – Håkon Hægland Jul 03 '16 at 09: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. – bliako Nov 09 '22 at 16:06

2 Answers2

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.
xxfelixxx
  • 6,512
  • 3
  • 31
  • 38
-1
my $res = system("perl -c test.pl");
unless ($res) {
    print "OK\n";
} else {
    print "Syntax error!\n";
}
gmoryes
  • 93
  • 1
  • 5
  • 2
    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. – Alexandr Evstigneev Jul 03 '16 at 12:06