Do not use the same variable name in two scopes where one scope is contained in another. For example,
- A lexical variable should not share the name of a package variable if the lexical variable is in a subscope of the global variable.
- A block should not declare a lexical variable with the same name as a lexical variable declared in any block that contains it.
...
This noncompliant code example declares the errmsg
identifier at file scope and reuses the same identifier to declare a string that is private in the report_error()
subroutine. Consequently, the program prints "The error is Local error" , rather than "The error is Global error.".
Code Block | ||||
---|---|---|---|---|
| ||||
$errmsg = "Global error";
sub report_error {
my $errmsg = shift(@_);
# ...
print "The error is $errmsg\n";
};
report_error("Local error");
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
$global_error_msg = "Global error";
sub report_error {
my $local_error_msg = shift(@_);
# ...
print "The error is $local_error_msg\n";
};
report_error("Local error");
|
When the block is small, the danger of reusing variable names is mitigated by the visibility of the immediate declaration. Even in this case, however, variable name reuse is not desirable. In general, the larger the declarative region of an identifier, the more descriptive and verbose should be the name of the identifier.
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL00DCL01-PL | low Low | probable Probable | medium Medium | P2 P4 | L3 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
B::Lint | 5.0 | .* masks earlier declaration in same scope | Implemented |
Related Guidelines
...
...
...
...
...
...
...
Automated Detection
Tool | Diagnostic |
---|---|
B::Lint | .* masks earlier declaration in same scope |
Bibliography
...
EXP30-PL. Do not use deprecated or obsolete functions 02. Expressions