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

321 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER
3
On

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