Area variables in coderefs, if perl, need an explanation of the strange behavior

Why are the $ copy_of_i values ​​returned by coderefs in @coderefs equal?

use Modern::Perl;
my @coderefs = ();
for (my $i = 0; $i < 5; $i++){
    push @coderefs, sub { 
        my $copy_of_i = $i;
        return $copy_of_i;
    };
}

say $coderefs[1]->();
say $coderefs[3]->();

I thought that $ copy_of_i would be local to every coderef added to @coderefs, and thus would contain the current value of $ i assigned to $ copy_of_i at this loop iteration. But if we show the values ​​of the pair $ copi_of_i with "say", we will see that they have the same values ​​as $ copy_of_i were not local to each newly created coderef. Why?

+4
source share
1 answer

, , $i , . , $copy_of_i . , , ; $i .

for (my $i = 0; $i < 5; $i++){
    my $copy_of_i = $i;
    push @coderefs, sub { 
      return $copy_of_i;
    };
}

, for my $i (0 .. 5) for (my $i = 0; $i < 5; $i++), ,

my @coderefs;
for my $i (0 .. 4) {
    push @coderefs, sub { 
      return $i;
    };
}
+4

Source: https://habr.com/ru/post/1570290/


All Articles