Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Numeric sorting WITHOUT <=>

by roboticus (Canon)
on Oct 10, 2012 at 02:52 UTC ( #998118=note: print w/ replies, xml ) Need Help??


in reply to Numeric sorting WITHOUT <=>

Just look at the definition of the <=> operator, and you should be able to code it up easily: $a <=> $b is negative when $a should precede $b, positive if $a should follow $b, and zero if $a and $b could be the same position. So if you're sorting numbers, you could just use $a - $b, as it returns appropriate values. Using $b - $a would sort in reverse:

$ cat ex_sort_odd.pl #!/usr/bin/perl use strict; use warnings; my @a; push @a, int(100*rand) for 1 .. 10; print "LIST: ", join(" ", @a), "\n"; my @b = sort { $a - $b } @a; print "ASC: ", join(" ", @b), "\n"; @b = sort { $b - $a } @a; print "DESC: ", join(" ", @b), "\n"; $ perl ex_sort_odd.pl LIST: 27 78 66 70 19 37 48 82 67 90 ASC: 19 27 37 48 66 67 70 78 82 90 DESC: 90 82 78 70 67 66 48 37 27 19

...roboticus

When your only tool is a hammer, all problems look like your thumb.


Comment on Re: Numeric sorting WITHOUT <=>
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2014-12-27 21:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls