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.