in reply to subs as args
A closure is an anonymous subroutine that's been created by another subroutine. The canonical example of a closure is a counter generator.
This seems like overkill, but it allows for two things:sub create_counter { my $counter = 0; return sub { $counter++ }; } # # # my $counter = create_counter(); while (&$counter < $Some_Value) { &DO_Stuff; }
Hence why closures are sometimes called "function templates". I've used closures as a way to help organize a set of functions that transformed an input in one of three basic ways. It was just that the transformation changed based on a set of definable parameters. (Take the 3rd thing in this instance, the 4th in that instance, but do the exact same thing.) Closures are also used to parse stuff. I believe it was tye (or tilly) that wrote a closure-based HTML parser as an example of functional programming some months back. Really interesting stuff.sub create_upper_bounded_counter { my ($upper_bound) = @_; my $counter = 0; return sub { $counter++ <= $upper_bound ? 1 : 0 }; } # # # my $bounded_counter = create_upper_bounded_counter(10); while (&$bounded_counter) { &Do_Stuff; }
------
We are the carpenters and bricklayers of the Information Age.
Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•closures are NOT anonymous subroutines necessarily
by merlyn (Sage) on Jul 08, 2002 at 16:45 UTC | |
by itub (Priest) on Jan 20, 2005 at 22:08 UTC | |
by dragonchild (Archbishop) on Jul 08, 2002 at 17:20 UTC |