Why don't I get a warning when I redeclare the Perl foreach control variable?

perl, variables, warnings

Solution

Actually, you only get warnings for redefinitions in the same scope. Writing:

use warnings;
my $i;
{
  my $i;
  # do something to the inner $i
}
# do something to the outer $i

is perfectly valid. I am not sure if the Perl internals handle it this way, but you can think of your `for` loop as being parsed as

{
  my $i;
  for $i ( ... ) { ... }
  # the outer scope-block parens are important!
};

Problem

Why is there no warning thrown for the redeclaration of `$i` in the following code? ``` #!/usr/bin/perl use strict; use warnings; use Data::Dumper; for my $i (1..3) { my $i = 'DUMMY'; print Dumper $i; } ```

Original source