Passing subroutines
- Referring to the sub without a parameter list gives a reference to
the subroutine
- The sort() function
uses this mechanism to allow custom sorts.
Sort functions
- Sort functions always have the variables $a and $b
defined as the parms.
- Comparisons use the three-way operators: cmp for strings, and <=> for numerics.
#!perl -w
use strict;
my @list = ( 5, 123, 42, 98.6 );
my @sorted1 = sort @list;
print "Default sort: @sorted1\n"; # not what we wanted
my @sorted2 = sort numerically @list;
print "Numerically: @sorted2\n"; # Now we're happy
sub numerically { return $a <=> $b; } Default sort: 123 42 5 98.6
Numerically: 5 42 98.6 123
Anonymous
subs
- An anonymous subroutine is a code block that doesn't have a name.
- You can use an anonymous subroutine simply by referring to it.
my @sorted3 = sort { $a <=> $b } @list;
- You can also return an anonymous subroutine from a function, as in:
sub sortstyle($) {
if ( $_[0] eq "numerically" ) {
return sub { $a <=> $b };
} else {
return sub { $a cmp $b };
}
my @sorted4 = sort sortstyle("numerically") @list;
|
|
|