So when you create 11 different anonymous subs that use $_, they are all pointing to the same memory location. If some code in some other place changes $_ (a likely scenario), then these anonymous subs will use that new value as well.
This is true, but there is a twist. For anonymous subroutines, Perl is smart enough to notice whether they are closures or not and if not it will actually reuse the same sub reference and its associated structures each time. See the following:
my (%withlex, %withglobal);
for (1 .. 10) {
my $ref = sub { return $_ };
$withglobal{$ref} = $ref;
}
for my $i (1 .. 10) {
my $ref = sub { return $i };
$withlex{$ref} = $ref;
}
print "Using lex num of subs is " . (keys %withlex) . "\n";
print "Using global num of subs is " . (keys %withglobal) . "\n";
which prints
Using lex num of subs is 10
Using global num of subs is 1
I also learned recently that a closure only captures the lexical variables the inner subroutine actually uses, so you can have issues like
Re: Eval doesn't see lexicals. So in the OP's case, there really is only one anonymous subroutine in the $_ version.