Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

reference to a sub

by Anonymous Monk
on Sep 11, 2005 at 06:37 UTC ( [id://491021]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I am not able to figure out why do we need reference to subroutines,and where can we use anonymous subroutines. Is there any specific use of anonymous subs? Any example of usage will be of great help... Thanks in advance!

Replies are listed 'Best First'.
Re: reference to a sub
by Zaxo (Archbishop) on Sep 11, 2005 at 07:30 UTC

    A dispatch table

    my %dispatch_table = ( foo => \&foo, bar => sub { mumble; }, );

    A sub returning a sub generated on the fly, maybe a closure,

    sub generate { my $foo = shift; sub { $foo }; }

    A variable routine to be called,

    sub callit { my $sub = shift; $sub->(@_); }

    Overriding a sub,

    # in a scope . . . local *foo = generate 'bar';

    The list goes on . . .

    After Compline,
    Zaxo

Re: reference to a sub
by sk (Curate) on Sep 11, 2005 at 07:34 UTC
    I think the question of when references to subs are used and anonymous subs are used is too broad.

    Here is a simple example of anonymous sub -

    my @sorted = sort { $a <=> $b } @unsorted;

    In the above block we passed an anonymous sub to sort. It is just easy (convenient) to write numeric sort that way than to define a sub that returns  $a <=> $b

    An example of sub ref is signal handling

    $SIG{INT} = \&catch_int;
    These examples are very simple. Others might contribute better examplese. Another thing i can think of is closures where you return a reference to a sub from inside another sub.

    -SK

Re: reference to a sub
by TedPride (Priest) on Sep 11, 2005 at 10:29 UTC
    Well, what if you have several different subs, one of which is to be chosen and used throughout your program based on the contents of a variable? You can either test the variable at each point in the program, duplicating your code and making an ugly mess, or you can test once and assign the sub reference to a variable, which is then used from then on.
Re: reference to a sub
by schwern (Scribe) on Sep 12, 2005 at 09:41 UTC
    Far more than you ever wanted to know about what you can do with anonymous subroutines can be found in the book Higher Order Perl by Mark-Jason Dominus.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://491021]
Approved by lidden
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-23 23:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found