Frequently-made mistakes in Perl
When writing a new script in Perl, I have wasted countless hours trying to find my mistake when the script bombs. Here are some of the common mistakes that are easy to make, especially if you try to write too much code before testing.
I would like to make ongoing additions to this tutorial, so if you have any "compilation errors" that are driving you batty, just send me an email, so I can add them to the list. Errors in logic that do not cause an aborted execution will be dealt with in a future tutorial.
Before giving you the list, I should mention that you SHOULD have access to the Error Log on your web server, so you can get an idea of what causes a crash. However, there is a simple way to direct these errors to your browser, so that you don't need to keep switching browser pages to find out where you went wrong. Just (temporarily) add the following lines to your script -- right under the path-to-Perl at the top.
BEGIN {
$| = 1; ### flushes STDOUT
open (STDERR, ">&STDOUT");
print "Content-type: text/plain\n\n<pre>";
}
Mistake #1: Forgetting to set proper permissions
This is the numero uno mistake for me. I forget this almost every time I start a new script. This mistake will obviously not be redirected to your browser. You will get the dreaded 500 Server Error. If you access your Error Log, you will see a message like Premature end of script headers. Go immediately to your FTP program and set the permissions to 755!
Mistake #2: Content-type header not in script
This again will cause a 500 Server Error in your browser. Your Error Log will say something like Malformed header from script. The line
print "Content-type: text/html\n\n";
MUST be in your script before any other print statement.
Note: For the rest of these, the error message you get may not point to the line where the mistake actually is. Perl doesn't always notice the mistake right away, so look at the lines BEFORE the line referred to in the message.
Mistake #3: No ending semicolon
The error message you will see for this will look something like, Syntax error at test.cgi line 13, near "print".
Mistake #4: No ending quotation mark
Again, you will get a Syntax error, and probably also Can't find string terminator '"' anywhere before EOF.
Mistake #5: Missing end parenthesis
This may cause another Syntax error, or sometimes Scalar found where operator expected, at test.cgi line 34, near "$title2".
Mistake #6: Missing curly brace
Syntax error and Missing right curly or square bracket at test.cgi line 20, at end of line.
Mistake #7: Quotes inside of quotes
Syntax error at test.cgi line 19, near ""Hello "world".
The last mistake is NOT a compilation error, but happens frequently enough that I will include it. It's also fairly easy to spot, even though the error is not "fatal".
Mistake #8: Not escaping special characters
A statement like
print "The price is $1.00 each.\n";
will cause output that's bound to look a little funny:
The price is .00 each.