Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re^2: Multiple Sort on selected column

by thundergnat (Deacon)
on Oct 18, 2012 at 19:31 UTC ( #999801=note: print w/ replies, xml ) Need Help??

in reply to Re: Multiple Sort on selected column
in thread Multiple Sort on selected column

I agree with one small caveat. It might be better to change the cmp_by sub to do a numeric comparison in addition to the string comparison. With just the cmp, 600000 sorts after 55000 but 400000 would sort before. The following will sort numerically largest to smallest then alphabetically.

sub cmp_by { my $result; for my $term (@_) { $result ||= +$b->{$term} <=> +$a->{$term} or $a->{$term} cmp $ +b->{$term}; } return $result; }

Comment on Re^2: Multiple Sort on selected column
Download Code
Re^3: Multiple Sort on selected column
by kennethk (Monsignor) on Oct 19, 2012 at 15:07 UTC
    Your point is, of course valid. However, you should test your code before running it. Your or is lower precedence than = (see Operator Precedence and Associativity). This is, for example, why the classic or die construct works so well. This also means your code will never actually sort by string - warnings would have told you that you are performing a comparison in void context. In addition, + is a no-op in unary operator context; you likely meant the numification ("Venus") operator, 0+. This will not suppress the string in numeric context warnings either, since you are still using a string in a numeric context.

    If you want to do auto-detection, you'd be better off using the Conditional Operator using looks_like_number from Scalar::Util:

    sub cmp_by { use Scalar::Util 'looks_like_number'; my $result = 0; for my $term (@_) { $result ||= looks_like_number($a) ? $a->{$term} <=> $b->{$term} : $a->{$term} cmp $b->{$term}; } return $result; }

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (10)
As of 2014-07-25 10:30 GMT
Find Nodes?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:

    Results (170 votes), past polls