Main Content

(Perl) Callbacks - what are they?

Archive - Originally posted on "The Horse's Mouth" - 2006-05-30 16:06:22 - Graham Ellis

In most programming applications, you'll write code that calls system functions or subroutines - for example, you'll write a program that reads data from a file (via a system call), splits the data into an array (perhaps via a further system call), and prints it out (through system calls).

On a few occasions - for example, when writing a GUI event handler or a use defined sort routine, you'll break the pattern. You'll call a system routine which will itself call back to a named piece of code that you have written. This concept isn't always easy for newcomers to grasp, and on yesterday's Perl course I wrote an extra training example to show what's really going on ...

In Perl, you sort using the sort function. Easy. But if you want to sort in a different way (perhaps sorting by the length of a string rather than alphabetically), you pass sort the name of a function that you've written which takes two input variables - globals $a and $b - and returns a negative, zero, or positive result if $a is less than, equal to, or greater than $b. In other words, the sort function that's Perl provided does the difficult bit of managing what needs to be compared with what, swapping items over as necessary, and minimising the number of comparisons you make; you're left with writing a simple piece of code that just ranks two records against each other.

Like to see what I mean?

I wrote a demo - a piece of code in Perl that sorts a list of hash keys based on the number of characters in the value held in the hash. The sort call was:
@names = sort bylength (keys(%hols));

I then re-wrote that line as:
@names = wingit ("bylength",keys(%hols));
and provided an extra piece of code called wingit that provided alternative functionality to Perl's sort, and calls bylength internally. Of course, this is purely illustrative and Perl's built-in sort will be much more efficient.

Both pieces of code work - full source code here.