Flimm
Flimm

Reputation: 150703

Why am I *not* getting this warning: "variable masks earlier declaration"?

Here's my entire script, crafted to include two variable with the same name, one of which is masking the other:

#!/usr/bin/env perl
use strict;
use warnings;

my $hi = "First hi";
print "$hi\n";

{
    my $hi = "Second hi";
    print "$hi\n";
}

print "$hi\n";

If I run this script, I get this output, and noticeably no warnings:

First hi
Second hi
First hi

If I remove the curly braces around the second $hi variable so that is in the same scope as the first $hi variable, I get this warning:

"my" variable $hi masks earlier declaration in same scope at hi.pl

However, I want this warning even when the variable is not in the same scope. I want the warning every time a variable name is shadowing another. How can I enable this warning? Is there a Perl Critic policy that I can enable that will warn me about this?

Upvotes: 3

Views: 335

Answers (2)

U. Windl
U. Windl

Reputation: 4325

The probable reason is:

my $a = 1;
# ...
{
   my $a = 2;
   # ...
}
# ...

may make sense, while

my $a = 1;
# ...
my $a = 2;
# ...

does not.

You might file an enhancement request to get warnings about the first case, too (as gcc does for C).

Upvotes: 1

fugu
fugu

Reputation: 6578

Did you try this:

Perl::Critic::Policy::Variables::ProhibitReusedNames;

Upvotes: 2

Related Questions