Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Numeric sorting WITHOUT <=>

by Marshall (Canon)
on Oct 10, 2012 at 03:41 UTC ( [id://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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2024-04-23 11:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found