next up previous contents
Next: Being Strict with Your Up: Logic Errors Previous: Logic Errors

Using the -w Command-Line Option

One of the most important features to combat logic errors is the -w command-line option, which causes warning messages to be displayed indicating questionable Perl code. Questionable code includes identifiers that are mentioned only once, scalar variables that are used before being set, redefined subroutines, references to undefined filehandles, and filehandles opened read-only that you are attempting to write on.

For example, can you find anything wrong with the following lines of code (debug1.pl)?

$foo = { };

$bar = 5;

print("$foa\n");

print("$bar\n");

You probably can't see anything wrong at first glance. In fact, this program compiles and runs without complaint. However, running this program with the -w option (perl -w test.pl) results in these error messages:

Identifier "main::foa" used only once: possible typo at test.pl line 4.
Identifier "main::foo" used only once: possible typo at test.pl line 1.
Use of uninitialized value at test.pl line 4.

With these error messages, the problem becomes obvious. Either the variable name $foo is misspelled in the assignment statement or the variable name $foa was misspelled in the print statement.

Always use the -w command-line option

The -w option is so useful that you should always use it. If you know that a specific line of code is going to generate an error message and you want to ignore it, use the $^W special variable.

For example, debug2.pl:

$foo = { };

$bar = 5;

$^W = 0;

print("$foa\n");

print("$bar\n");

$^W = 1;

eliminates the display of the

Use of uninitialized value at test.pl line 4.

error message.

Unfortunately, this technique will not stop all messages, and the placement of the $^W=0; statement seems to affect whether the message will be suppressed.

Caution This feature did not seem to be too stable in my version of Perl. If you can't get it to work in your version, don't spend too much time trying to find the problem. It simply may not work properly in your version of Perl, either.


next up previous contents
Next: Being Strict with Your Up: Logic Errors Previous: Logic Errors
dave@cs.cf.ac.uk