Perl provides the my() and our() functions specifically for declaring variables.

However, Perl allows any variable to be referenced, even if it is not declared or initialized. If an uninitialized value is requested, Perl supplies a default undef value. Depending on the context, the undef value may be interpreted as 0, false, or an empty string.

Because Perl programs are typically not explicitly compiled before they are run, they can suffer from typographic errors in variable names. A variable whose name is typed incorrectly will appear as an undeclared variable to the Perl interpreter and consequently will contain the undef value instead of the value of the intended variable.

Because of the hazard of mistyped variables, all variables should be declared before use.

Noncompliant Code Example

This noncompliant code example contains a typo in its print statement.

my $result = compute_number();
print "The result is $reuslt\n";   # oops!

It causes the program to print the following useless output:

The result is

and continue execution.

Compliant Solution

This compliant solution corrects the typo, causing the program to correctly print the result of compute_number().

my $result = compute_number();
print "The result is $result\n";

Risk Assessment

Using undeclared variables usually can lead to incorrect results and surprising program behavior.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

DCL33-PL

Low

Probable

High

P2

L3

Automated Detection

Tool

Diagnostic

use warnings;

Name .* used only once. possible typo

use strict;Global symbol .* requires explicit package name

Perl::Critic

 

Policy::TestingAndDebugging::RequireUseWarnings

Policy::TestingAndDebugging::RequireUseStrict

Related Guidelines

Bibliography

 


2 Comments

  1. Anonymous

    "use strict;" catches those errors and produces a compile-time error for each variable used before it's declared (with my or our). I'm surprised that it's not mentioned, seeing as it's the first best practice any new Perl programmer is likely to be told about.

    -w is also not recommended; "use warnings;" is more flexible.

    The relevant Perl::Critic policies are https://metacpan.org/module/Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings and https://metacpan.org/module/Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict .

    1. True, we discuss proper warnings in MSC02-PL. Run programs with full warnings and strict checking

      I've updated this rule, but there are others that also involve -w. We'll be fixing those shortly the same way we fixed this one.