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 typographical 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 therefore contain the undef
value instead of the value of the intended variable.
Due to Because of the hazard of mistyped variables, all variables should be declared before use.Perl's -w
command-line option causes a warning to be issued for any variable name in the code that appears exactly once in the code, which might indicate a mistyped variable name.
Noncompliant Code Example
...
It causes the program to print the following useless output:
Code Block |
---|
The result is |
...
Code Block | ||||
---|---|---|---|---|
| ||||
my $result = compute_number(); print "The result is $result\n"; |
...
CERT C Secure Coding Standard: DCL31-C. Declare identifiers before using them
Risk Assessment
Using undeclared variables usually can lead to incorrect results and surprising program behavior.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL33-PL | lowLow | probableProbable | highHigh | P3P2 | L3 |
Automated Detection
Tool | Diagnostic |
---|---|
-w | 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
[CPAN] | Elliot Shank, Perl-Critic-1.116, Policy::TestingAndDebugging::RequireUseWarnings and Policy::TestingAndDebugging::RequireUseStrict |
[Wall 2011] | perldiag, perlfunc |
...
DCL32-PL. Every module must return a true value 01. Declarations and Initialization 02. Expressions