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.


In reply to Re: Why callbacks? by Joost
in thread Why callbacks? by pileofrogs

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.