One of the first things I try to learn in an unfamiliar programming language is how it handles closures. Their semantics are often intertwined with how the language handles scop
Closures only close over lexical variables; $_
is normally a global variable.
In 5.10 and above, you can say my $_;
to have it be lexical in a given scope (though in 5.18 this was retroactively declared to be experimental and subject to change, so better to use some other variable name).
This produces the output you expected:
use strict;
use warnings;
use 5.010;
my @closures;
foreach my $_ (1..3) {
# create some closures
push @closures, sub { say "I will remember $_"; };
}
foreach (@closures) {
# call the closures to see what they remember
# the result is not obvious
&{$_}();
}