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
&{$_}();
}
$_ is a global variable and should not be used in closure. Before using it assign this to a lexically scoped variable as shown bewlow. This will produce expected o/p.
#!/usr/bin/perl -w
use strict;
my @closures;
foreach (1..3) {
my $var = $_;
push @closures, sub { print "I will remember $var"; };
}
foreach (@closures) {
$_->();
print "\n";
}