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

前端 未结 2 1634
深忆病人
深忆病人 2021-01-11 19:42

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;

         


        
相关标签:
2条回答
  • 2021-01-11 20:21

    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!
    };
    0 讨论(0)
  • 2021-01-11 20:30

    You would get a warning if you redeclare a my, our or state variable in the current scope or statement. The first $i isn't actually a lexical variable. You can prove this using Devel::Peek:

    use Devel::Peek;   
    
    for my $i (1) {
        Dump $i;
    }  
    
    SV = IV(0x81178c8) at 0x8100bf8
    REFCNT = 2
    FLAGS = (IOK,READONLY,pIOK)
    IV = 1
    

    There's no PADMY flag in FLAGS, which would indicate that $i is a lexical variable, declared with my.

    0 讨论(0)
提交回复
热议问题