Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 undef.

Wiki Markup
            Perl has a large number of builtin functions, they are described on the {{perlfunc}} manpage \[[Wall 2011|AA. Bibliography#Manpages]\]. Perl also has a handful of reserved keywords such as {{while}}; they are described on the {{perlsyn}} manpage \[[Wall 2011|AA. Bibliography#Manpages]\].

Do not use an identifier for a subroutine that has been reserved for a builtin function or keyword.

Noncompliant Code Example

...

Code Block
bgColor#ffcccc
langperl

$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();

...

This compliant solution initializes the localized variable to the old value. So , so it correctly prompts the user for a password.

Code Block
bgColor#ccccff
langperl

$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();

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

DCL04-PL

low Low

probable Probable

medium Medium

P2 P4

L3

Automated Detection

  

 

ToolDiagnostic
Perl::CriticVariables::RequireInitializationForLocalVars 

Bibliography

  

...

...

...

 

 
 
 

...

Image Added Image Added Image Added|http://search.cpan.org/dist/Perl-Critic/lib/Perl/Critic/Policy/Variables/RequireInitializationForLocalVars.pm] \[[Wall 2011|AA. Bibliography#Manpages]\] [perlfunc|http://perldoc.perl.org/perlfunc.html], [perlsyn|http://perldoc.perl.org/perlsyn.html] Image Removed      01. Declarations and Initialization      DCL32-PL. Every module must return a true value