Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

(jeffa) Practical Use For What jeffa Thought A Closure Was (3Re: Style Question on Closures)

by jeffa (Bishop)
on Jan 01, 2002 at 23:26 UTC ( #135537=note: print w/replies, xml ) Need Help??

in reply to Re: Re: Style Question on Closures
in thread Style Question on Closures

There are practical uses for call-backs. One use is to provide some user of a Perl module a way to modify the behavior of that module. Here is a very simple example:
use strict; package Foo; use Carp; sub new { my ($class,$msg) = @_; my $self = {msg => $msg}; return bless $self,$class; } sub print_me { my ($self,$cb) = @_; croak "not a code ref" unless ref $cb eq 'CODE'; return $cb->($self->{'msg'}); } package main; my $foo = Foo->new('hello world'); print $foo->print_me(sub {ucfirst shift}), "\n";
Now the user can specify how they want the message printed. Like i said, a very simple example, but i am sure you can imagine this module doing a lot more behind the scenes. In these cases, providing a call-back instead of providing a list of choices can make a module more flexible, and keep you from maintaining that list of choices.

UPDATE - drats. Just when i though i knew what a closure was .... perrin pointed out that this is indeed, not a closure ... a good example for a anonymous subs maybe, but not a closure. I stand corrected and apologetic to the 13 people that voted this node up.


(the triplet paradiddle)
  • Comment on (jeffa) Practical Use For What jeffa Thought A Closure Was (3Re: Style Question on Closures)
  • Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://135537]
[Discipulus]: LA use Perl: traversing a dir tree is simple; foreach file mp3 $sec+= use Mp3::Info
[Lady_Aleena]: Discipulus, I was able to get the sum of the seconds on the command line using awk. Then I ran the result through a perl script and got the result. It came bach with 4 days, 9 hours, 56 minutes, 43 seconds.
[Lady_Aleena]: s/bach/back/;
[Discipulus]: gired anyway is the intermediate state between hired and fired (and vice versa;)
[Lady_Aleena]: Discipuluis, I don't know if I want to fight with File::Find. File::Find and I are not friends.
[Discipulus]: 4 day Bach is too muche even for me
[Discipulus]: LA you know who is paco?
[Lady_Aleena]: Disc, nope.
[Discipulus]: ahi ahi ahi!!

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2017-04-23 20:35 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (432 votes). Check out past polls.