Документация
HTML CSS PHP PERL другое

Section 7.3.  Callbacks

 
Previous
Table of Contents
Next

7.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, we 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);

find starts at the current directory (.) and locates each file or directory. For each item, we call 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, we'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 to use the name only once, so we can write the previous code using an anonymous subroutine, such as:

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

find(
  sub {
    print "$File::Find::name found\n";
  },
  @starting_directories,
);


Previous
Table of Contents
Next
© 2000- NIV