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?sub mysort { my ($direction) = @_; ( $hash{$a}{$orderby} <=> $hash{$b}{$orderby} || $hash{$a}{$orderby} cmp $hash{$b}{$orderby}) * ($direction eq "DESC" ? -1 : 1); }
This keeps the code clean and keeps the operations to be done in each comparison close to the minimum, without using reverse.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; } }
Roger
In reply to Re: sort direction
by Roger_B
in thread sort direction
by rsiedl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |