in reply to Why are closures cool?
sub multiply_by { my $multiplier = $_[0]; return sub { return $_[0] * $multiplier; } } my $times2 = multiply_by(2); my $times10 = multiply_by(10); print &$times2(4), "\n"; print &$times2(6), "\n"; print &$times10(4) ,"\n"; # Results: # 8 # 12 # 40
You can also use closures to enforce strict data encapsulation, since they allow you to create variables that simply don't exist to the outside world.
Damian Conway's excellent book Object Oriented Perl has some good examples of real reasons you might want to use closures in Perl. He certainly explains it better than this off-the-cuff response does ;-)
|
|---|