Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: sort direction

by Roger_B (Scribe)
on Oct 07, 2005 at 12:20 UTC ( [id://498254]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


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 12: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:>*

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://498254]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.