6.3 Callbacks

A subroutine reference is often used for a callback. A callback defines what to do when a subroutine reaches a particular place in an algorithm.

For example, the File::Find module exports a find subroutine that can efficiently walk through a given filesystem hierarchy in a fairly portable way. In its simplest form, you give the find subroutine two parameters: a starting directory and "what to do" for each file or directory name found recursively below that starting directory. The "what to do" is specified as a subroutine reference:

use File::Find;
sub what_to_do {
  print "$File::Find::name found\n";
my @starting_directories = qw(.);

find(\&what_to_do, @starting_directories);

In this case, find starts at the current directory (.) and locates each file or directory. For each item, a call is made to the subroutine what_to_do( ), passing it a few documented values through global variables. In particular, the value of $File::Find::name is the item's full pathname (beginning with the starting directory).

In this case, you're passing both data (the list of starting directories) and behavior as parameters to the find routine.

It's a bit silly to invent a subroutine name just to use the name only once, so you can write the previous code using an anonymous subroutine, such as:

use File::Find;
my @starting_directories = qw(.);

  sub {
    print "$File::Find::name found\n";