Friday, July 08, 2005

Perl Syntax Error Not Caught at Compile Time

I have a bad habit of munging the syntax for perl 'open' commands. Instead of the correct syntax, e.g.
open (TESTFH, "< test.txt") or die "Couldn't open data file: $!";

I tend to misplace the right parentheses, like this:
open (TESTFH, "< test.txt" or die "Couldn't open data file: $!");

Consider this test script:
open (TESTFH, "< test.txt" or die "Couldn't open data file: $!");
while () {
$content .= $_;
print $content or die "Couldn't print data: $!";
close TESTFH or die "Couldn't close data file: $!";

This code will generate an error like this:
$ ./
Couldn't close data file: Bad file descriptor at ./ line 7.

That is, the file handle was never opened properly, but did not fail. The WHILE block does not execute and the print statement has nothing to print, but does not fail. A simple syntax error which should have been caught at compile time has promulgated through to a nasty and poorly-reported run time error.

Unfortunately, the use of the 'strict' pragma ('use strict;') does NOT catch this error at compile time.

This example was generated on Perl v5.8.6 for darwin-thread-multi-2level, but I have seen it on Linux as well. Earlier versions of Perl 5 have this problem. I haven't tested Perl 6 yet.

No comments:

Post a Comment