My first thought was:
sub mysort {
my ($direction) = @_;
( $hash{$a}{$orderby} <=> $hash{$b}{$orderby}
||
$hash{$a}{$orderby} cmp $hash{$b}{$orderby})
*
($direction eq "DESC" ? -1 : 1);
}
This minimises duplication and cleans up the source code.
But it still means evaluating the direction each time. All those wasted cycles!
How about a closure?
my $orderby = "age"; # or name, dob, etc
my $direction = "ASC"; # or DESC
my $sortfunc = getsort($direction);
foreach my $id (sort $sortfunc keys %hash) {
print "$id - $hash{$id}{$orderby}\n";
} # end-foreach
sub getsort {
my ($direction) = @_;
my $sense = $direction eq "DESC" ? -1 : 1;
return sub {
( $hash{$a}{$orderby} <=> $hash{$b}{$orderby}
||
$hash{$a}{$orderby} cmp $hash{$b}{$orderby})
*
$sense;
}
}
This keeps the code clean and keeps the operations to be done in each comparison close to the minimum, without using
reverse.
Roger