Perl has a large number of builtin functions, they are described on the perlfunc
manpage [Wall 2011]. Perl also has a handful of reserved keywords such as while
; they are described on the perlsyn
manpage [Wall 2011].
Do not use an identifier for a subroutine that has been reserved for a builtin function or keyword.
Noncompliant Code Example
This noncompliant code example authenticates the user to enter a password, but only if the $passwd_required
variable is defined.
$passwd_required = 1; # ... sub authenticate_user { local $passwd_required; if (defined $passwd_required) { print "Please enter a password\n"; # ... get and validate password } else { print "No password necessary\n"; } } authenticate_user();
The call to local temporarily sets $passwd_required
to the uninitialized value undef
; it does not maintain its previous value of 1
. Consequently, when the program executes, it incorrectly prints No password necessary
.
Compliant Solution
This compliant solution initializes the localized variable to the old value. So it correctly prompts the user for a password.
$passwd_required = 1; # ... sub authenticate_user { local $passwd_required = $passwd_required; if (defined $passwd_required) { print "Please enter a password\n"; # ... get and validate password } else { print "No password necessary\n"; } } authenticate_user();
Risk Assessment
Uninitialized variables can cause surprising program behavior.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
DCL04-PL |
low |
probable |
medium |
P2 |
L3 |
Automated Detection
|
Tool |
|
Diagnostic |
|
Perl::Critic |
Variables::RequireInitializationForLocalVars |
|
|
|
Bibliography
[Conway 05] pg. 78 "Initialization"
[CPAN] Elliot Shank, Perl-Critic-1.116 Variables::RequireInitializationForLocalVars
[Wall 2011] perlfunc, perlsyn
01. Declarations and Initialization DCL32-PL. Every module must return a true value