in reply to sort direction

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

Replies are listed 'Best First'.
Re^2: sort direction
by Perl Mouse (Chaplain) on Oct 07, 2005 at 16:32 UTC

    This keeps the code clean and keeps the operations to be done in each comparison close to the minimum, without using reverse.

    But you're still doing a multiplication for on each comparison. Why avoid using reverse?

    Perl --((8:>*