If demerphq's great post lost you, let me try a simpler example. There's really no difference between an "anonymous" closure and one that isn't. I think it's really a misnomer in the perl docs to link it so closely to anonymous functions. I read somewhere (looked but couldn't find the reference) that the sub keyword is really just doing this behind the scenes (apart from forward declarations, anyway):
sub foo { print "hello world" }; # more or less equivalent to: BEGIN { *foo = sub { print "hello world" }; }
The reason that such a distinction is made between "regular" subroutine declarations and anonymous subroutine declarations is that most of the utility of having closures in the language comes from applying them to anonymous subroutines that are assigned multiple times on the fly.
Consider the following example with simple counters. The anonymous subroutine created in the counter_gen subroutine is compiled only once, but each time counter_gen is called, the resulting reference winds up using a different copy of $j. The anonymous subroutine gets a copy of the lexical environment at the time it is assigned. This allows me to create two counters with different starting points using the same code. However, in usage, they work just like the regular, named counter created earlier.
#!/usr/bin/perl use strict; use warnings; my $i = 1; sub counter_i { $i++ } sub counter_gen { my $j = shift; return sub { $j++ } } my @counters = ( \&counter_i, counter_gen(5), counter_gen(10) ); for ( 1 .. 10 ) { for my $c ( @counters ) { print $c->(), " "; } print "\n"; }
Prints
1 5 10 2 6 11 3 7 12 4 8 13 5 9 14 6 10 15 7 11 16 8 12 17 9 13 18 10 14 19
-xdg
Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
In reply to Re: Nailing down closures!
by xdg
in thread Nailing down closures!
by mattford63
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |