Skip to content

Instantly share code, notes, and snippets.

@pozorvlak
Created October 27, 2017 17:41
Show Gist options
  • Save pozorvlak/9c6fadd6b2afef2a83d51f4368474a8b to your computer and use it in GitHub Desktop.
Save pozorvlak/9c6fadd6b2afef2a83d51f4368474a8b to your computer and use it in GitHub Desktop.
Closure weirdness in Perl
Updating a single variable in-place: closures get the new value because they fetch it from the lexical scope
$ cat closures.pl
my @closures;
for (my $i = 0; $i < 3; $i++) {
push @closures, sub { print "$i\n"; };
}
for my $fn (@closures) {
$fn->();
}
$ perl closures.pl
3
3
3
Standard Perl foreach loop: it looks like each iteration gets a new copy of the variable
$ cat closures_foreach.pl
my @closures;
for my $i (0..3) {
push @closures, sub { print "$i\n"; };
}
for my $fn (@closures) {
$fn->();
}
$ perl closures_foreach.pl
0
1
2
3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment