On Thu, Sep 9, 2010 at 07:20, Jatin Davey <jasho...@cisco.com> wrote: > Hi > > I am a newbie to Perl , I was reading through one of the beginner level > books on perl. I did not understand the concept of "Callbacks" and i have > the following questions on it: > > 1. What are they ? > > 2. Why do we need them ? > > 3. What useful purpose do they achieve ? > > I was reading the following code to understand it but could not comprehend. > > *Code:* > > #!/usr/bin/perl > use warnings; > use strict; > use File::Find; > find ( \&callback, "/"); > > sub callback { > print $File::Find::name, "\n"; > } > > *End Of Code:* > > Thanks > Jatin >
[Callbacks][0] are a method of generalizing code. A classic example is sorting. A sorting algorithm is completely general except for one thing: how to compare the data being sorted. So most sorting algorithms are written to take a callback as well as the data to be sorted. The callback knows how to compare two items that are being sorted. #!/usr/bin/perl use strict; use warnings; sub insertion_sort { my $compare = shift; my @sorted; OUTER: for my $item (@_) { for my $i (0 .. $#sorted) { if ($compare->($sorted[$i], $item) == 1) { #insert item before the sorted item #that is larger than it splice @sorted, $i, 0, $item; next OUTER; } } #this must be the biggest item so far, put it at the end push @sorted, $item; } return @sorted; } sub sort_numerically { $_[0] <=> $_[1] } sub sort_lexically { $_[0] cmp $_[1] } my @unsorted = (4, 3, 2, 6, 5, 1, 10, 100, 20); print join(", ", insertion_sort \&sort_numerically, @unsorted), "\n"; print join(", ", insertion_sort \&sort_lexically, @unsorted), "\n"; Now, creating sort_numerically is a pain, it would be much better if we could just create the comparison function when we needed it. Luckily Perl 5 has this capability: [anonymous subroutines][1] (you might hear some people calling them lambdas). In the previous example I could have just said print join(", ", insertion_sort sub { $_[0] <=> $_[1] }, @unsorted), "\n"; print join(", ", insertion_sort sub { $_[0] cmp $_[1] }, @unsorted), "\n"; One of the benefits of doing this is that it is now easy to reverse the sort order: print join(", ", insertion_sort sub { $_[1] <=> $_[0] }, @unsorted), "\n"; print join(", ", insertion_sort sub { $_[1] cmp $_[0] }, @unsorted), "\n"; [0]: http://en.wikipedia.org/wiki/Callback_(computer_science) [1]: http://en.wikipedia.org/wiki/Anonymous_function -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/