The most important pragma is strict. This pragma generates compiler errors if unsafe programming is detected. There are three specific things that are detected:
Symbolic references use the name of a variable as the reference to the variable. They are a kind of shorthand widely used in the C programming language, but not available in Perl.
The following program that uses symbolic references via the following procedure:
The Perl code is strict.pl:
my($foo) = "Testing."; my($ref); $ref = \$foo; print("${$ref}\n"); # Using a real reference $ref = $foo; print("${$ref}\n"); # Using a symbolic reference use strict; print("${$ref}\n");
When run with the command perl 15lst05.pl, this program displays:
Testing. Can't use string ("Testing.") as a SCALAR ref while "strict refs" in use at 15lst05.pl line 14.
The second print statement, even though obviously wrong, does not generate any errors. Imagine if you were using a complicated data structure such as the ones described in Chapter on References. You could spend hours looking for a bug like this. After the strict pragma is turned on, however, a runtime error is generated when the same print statement is repeated. Perl even displays the value of the scalar that attempted to masquerade as the reference value.
The strict pragma ensures that all variables that are used are either local to the current block or they are fully qualified. Fully qualifying a variable name simply means to add the package name where the variable was defined to the variable name. For example, you would specify the $numTables variable in package Room by saying $Room::numTables. If you are not sure which package a variable is defined in, try using the dispSymbols() function from the previous pogram in this chapter. Call the dispSymbols() function once for each package that your script uses.
The last type of error that strict will generate an error for is the non-quoted word that is not used as a subroutine name or file handle. For example, the following line is good:
$SIG{'PIPE'} = 'Plumber';
And this line is bad:
$SIG{PIPE} = 'Plumber';
Perl 5, without the strict pragma, will do the correct thing in the bad situation and assume that you meant to create a string literal. However, this is considered bad programming practice.
Tip Always use the strict pragma in your scripts. It will take a little longer to declare everything, but the time saved in debugging will more than make up for it.