How to check if a Perl script doesn't have any compilation errors?

I am calling many Perl scripts in my Bash script (sometimes from csh also).

At the start of the Bash script I want to put a test which checks if all the Perl scripts are devoid of any compilation errors.

One way of doing this would be to actually call the Perl script from the Bash script and grep for "compilation error" in the piped log file, but this becomes messy as different Perl scripts are called at different points in the code, so I want to do this at the very start of the Bash script.

Is there a way to check if the Perl script has no compilation error?


Solution 1:

Beware!!

Using the below command to check compilation errors in your Perl program can be dangerous.

$ perl -c yourperlprogram

Randal has written a very nice article on this topic which you should check out

  • Sanity-checking your Perl code (Linux Magazine Column 91, Mar 2007)

Quoting from his article:

Probably the simplest thing we can tell is "is it valid?". For this, we invoke perl itself, passing the compile-only switch:

perl -c ourprogram

For this operation, perl compiles the program, but stops just short of the execution phase. This means that every part of the program text is translated into the internal data structure that represents the working program, but we haven't actually executed any code. If there are any syntax errors, we're informed, and the compilation aborts.

Actually, that's a bit of a lie. Thanks to BEGIN blocks (including their layered-on cousin, the use directive), some Perl code may have been executed during this theoretically safe "syntax check". For example, if your code contains:

BEGIN { warn "Hello, world!\n" } 

then you will see that message, even during perl -c! This is somewhat surprising to people who consider "compile only" to mean "executes no code". Consider the code that contains:

BEGIN { system "rm", "-rf", "/" } 

and you'll see the problem with that argument. Oops.

Solution 2:

Apart from perl -c program.pl, it's also better to find warnings using the command:

perl -w program.pl

For details see: http://www.perl.com/pub/2004/08/09/commandline.html