Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Why callbacks?

by Joost (Canon)
on Mar 30, 2007 at 17:51 UTC ( [id://607552]=note: print w/replies, xml ) Need Help??


in reply to Why callbacks?

Am I missing the beauty of callbacks? What are they for? Why would someone use them instead of just returning a hash ref or something like that?
A simple example of the beaty of callbacks is the sort function: sort() can sort a list of any kind of data as long as the elements in the list can be compared to each other as being "less", "the same" or "more":
sub revcmp { # note that for brevity sort() does not use the normal way # of passing variables to its callback, but sets # global variables $a and $b reverse($a) cmp reverse($b); } my @strange = sort \&revcmp @list;
You cannot really do this any other way without either losing flexibility in the sort order or having to write your own sorting algorithm.

You can also view map {}, grep {}, foreach {} and most other looping constructs as being using callbacks, except that you can't directly pass in another subroutine, you need to specify a literal code block or expression. Perl just treats these specially. For example in Ruby and newish JavaScript versions, map, grep/filter and foreach ARE just functions accepting callbacks.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (1)
As of 2024-04-19 00:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found