When a package variable is declared
local, it is often assumed that the package variable's contents are duplicated and stored in the local variable. This is not so; the local variable is set to
undef, just like any other uninitialized variable. Consequently, local variables must be initialized. They may be initialized with the contents of the package variable. If they are meant to be uninitialized, they should be explicitly set to
Noncompliant Code Example
This noncompliant code example authenticates the user to enter a password, but only if the
$passwd_required variable is defined.
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.
This compliant solution initializes the localized variable to the old value, so it correctly prompts the user for a password.
Uninitialized variables can cause surprising program behavior.
|[Conway 2005]||"Initialization," p. 78|
|[CPAN]||Elliot Shank, Perl-Critic-1.116 Variables::RequireInitializationForLocalVars|
|[Wall 2011]||perlfunc, perlsyn|