Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Numeric sorting WITHOUT <=>

by Marshall (Prior)
on Oct 10, 2012 at 03:41 UTC ( #998124=note: print w/ replies, xml ) Need Help??


in reply to Numeric sorting WITHOUT <=>

If you want to sort by a numeric value, using the "spaceship" operator "<=>" is THE way to go!

If you sort by "ascii order" on a numeric field, then you have to have the same number of "ascii digits" or the sort will not work.

!/usr/bin/perl -w use strict; my %jetsons = ( 7 => 'Judy', 10 => 'Jane', 11 => 'George', 2 => 'Elroy', 100=> 'Rosey', 1 => 'Astro', 19 => 'Mr. Spacely', 22 => 'Mr. Cogswell'); foreach my $key (sort { $a<=>$b } keys %jetsons) { printf "%-5s %s\n", $key, $jetsons{$key}; } __END__ 1 Astro 2 Elroy 7 Judy 10 Jane 11 George 19 Mr. Spacely 22 Mr. Cogswell 100 Rosey
Use <=> to compare numeric values.
Use cmp to compare string values.

I often advocate date/time strings like this: 2010-10-03 0837
A string like that (YYYY-MM-DD HHMM) with leading zeros, can be compared against other date/times in a simple way (ASCII sort), but the leading zeroes are important! A simple ASCII sort order will work, but ONLY if the fields are of constant width and have leading zeroes.


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://998124]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (9)
As of 2014-08-21 18:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (142 votes), past polls