in reply to sort direction

Interestingly, no one suggested using different sort functions.

sub mysort_asc { $hash{$a}{$orderby} <=> $hash{$b}{$orderby} || $hash{$a}{$orderby} cmp $hash{$b}{$orderby} } sub mysort_desc { $hash{$b}{$orderby} <=> $hash{$a}{$orderby} || $hash{$b}{$orderby} cmp $hash{$a}{$orderby} } my $sort_func = $direction eq 'DESC' ? \&mysort_desc : \&mysort_asc; foreach my $id (sort { &$sort_func } keys %hash) { #... }
(untested)

Replies are listed 'Best First'.
Re^2: sort direction
by Roy Johnson (Monsignor) on Oct 07, 2005 at 15:36 UTC
    How about dispatching the direction to get the appropriate sort function?
    my %sorts = ( DESC => sub { $hash{$b}{$orderby} <=> $hash{$a}{$orderby} or $hash{$b}{$orderby} cmp $hash{$a}{$orderby} }, ASC => sub { $hash{$a}{$orderby} <=> $hash{$b}{$orderby} or $hash{$a}{$orderby} cmp $hash{$b}{$orderby} } ); my $sort_func = $sorts{$direction}; foreach my $id (sort { &$sort_func } keys %hash) {
    Update: do the hash lookup only once, not for every comparison.

    Caution: Contents may have been coded under pressure.