Created
October 27, 2017 17:41
-
-
Save pozorvlak/9c6fadd6b2afef2a83d51f4368474a8b to your computer and use it in GitHub Desktop.
Closure weirdness in Perl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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