Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does perl not warn when redeclaring a variable in an inner scope?

Tags:

perl

As a bit of a perl novice, I just ran into a bug where I accidentally did something like (example simplified):

my $i=0;
 for(my $i=0;$i<10; $i++)
  {
    print $i;
  }
print $i; # $i is zero, my code expected 9

From Why don't I get a warning when I redeclare the Perl foreach control variable? I understand that this behavior is expected; I should not get a warning unless the re-declaration is in the same scope.

However, I can not understand why this is the case. Why would perl not issue a warning here? It seems to me that it would be a likely cause of errors, and usually not intended. Is there some common case where this is normal programming style, so that the warning would be annoying?

like image 432
tengfred Avatar asked May 02 '13 12:05

tengfred


1 Answers

Perl doesn't tend to warn for style issues, but I find it hard to believe that someone would intentionally want to have the same var name at different scope depths.

The only case where it might be useful that comes to mind is

{
    my $x = $x;
    ... do some something that changes $x ...
}
# $x is restored here.

On the plus side, there is a perlcritic rule to identify such a problem.

like image 112
ikegami Avatar answered Oct 23 '22 19:10

ikegami