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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|