in reply to sort direction
Accoring to the documentation for sort, it expects a function that returns -1, 0, or 1 for (a<b),(a==b),(a>b), respectively. So, that's all your sub needs to do.
# note passing your sub $a and $b foreach my $id (sort { mysort($direction,$a,$b) } keys %hash) { print "$id - $hash{$id}{$orderby}\n"; } # end-foreach sub mysort { my ($direction, $_a, $_b) = @_; my $result = $hash{$_a}{$orderby} <=> $hash{$_b}{$orderby} || $hash{$_a}{$orderby} cmp $hash{$_b}{$orderby}; # default to ascending, but if the dir is 'DESC', we # return the *opposite* answer return ($direction eq 'DESC') ? -($result) : $result; }
Untested, of course, but the idea should be basically sound. If I understand what you're trying to accomplish, though, you might take a different approach.
# we pass the sub the actual values to compare foreach my $id ( sort { mysort($direction,$hash{$a}{$orderby},$hash{$b}{$orderby}) } +keys %hash ) { print "$id - $hash{$id}{$orderby}\n"; } # end-foreach sub mysort { my ($direction, $_a, $_b) = @_; # generalized, simplified comparison my $result = $_a <=> $_b || $_a cmp $_b; # default to ascending, but if the dir is 'DESC', we # return the *opposite* answer return ($direction eq 'DESC') ? -($result) : $result; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: sort direction
by Roger_B (Scribe) on Oct 07, 2005 at 22:30 UTC | |
by radiantmatrix (Parson) on Oct 11, 2005 at 16:26 UTC | |
by BrowserUk (Patriarch) on Oct 11, 2005 at 19:14 UTC | |
by Perl Mouse (Chaplain) on Oct 12, 2005 at 08:49 UTC | |
by BrowserUk (Patriarch) on Oct 12, 2005 at 09:08 UTC | |
by BrowserUk (Patriarch) on Oct 12, 2005 at 09:21 UTC |