Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Twice the pleasure of sorting a hash

by ph0enix (Friar)
on Apr 26, 2004 at 09:57 UTC ( [id://348123]=note: print w/replies, xml ) Need Help??


in reply to Twice the pleasure of sorting a hash

Use following code for sorting

sort {$tmp = $saved_key{$b} <=> $saved_key{$a}; $tmp = $a cmp $b if ($tmp == 0); $tmp} keys %saved_key

Temporary variable is not needed of course

Replies are listed 'Best First'.
Re: Re: Twice the pleasure of sorting a hash
by halley (Prior) on Apr 26, 2004 at 13:52 UTC
    While your code works, it's one of those occasions where you're making code less readable by being more explicit.
    ... sort { $h{$b} <=> $h{$a} || $a cmp $b } keys %saved_key;
    Unlike C or Java, the Perl operator || keeps the actual true value. (C or Java would just return 1; but they don't have <=> either.) This means (among other things) that Perl can cascade a number of possible criteria in a single statement. By avoiding the visual clutter of temporary variables and unnecessary checks against zero, your code can be more readable.

    This is the Perl idiom. List each criteria from most important to least important. The first criteria which returns a -1 or 1 will decide the sort order; any criteria returning 0 will fall through to the next part of the expression.

    my @sorted = sort { $hash{$b} <=> $hash{$a} || $a cmp $b || func($a) <=> func($b) || $other{name}{$b} cmp $other{name}{$a} } @unsorted;
    I find that a newline after each criteria helps the reader immediately understand what's going on. (The extra spacing on each line is optional.)

    This newline on each phase technique is useful of any of the Perl-style "list pipelines" which are common, such as those with colorful names like the Schwartzian Transform or the Orcish Maneuver.

    --
    [ e d @ h a l l e y . c c ]

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://348123]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-24 06:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found