Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Numeric sorting WITHOUT <=>

by Marshall (Abbot)
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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://998124]
[LanX]: they have a constitutional referendum in turkey, kind of "do you want a dictator" and everybody opting no gets problems ...
[Corion]: LanX: Random Auto Expand?
[Corion]: LanX: Well, everybody opting "yes" will also get problems. The question is more like "Do you want problems now or problems later?"
[LanX]: and the AA had posters with a big say NO with a small "to alcohol"
[ambrus]: LanX: is it the kind of free and secret vote where there's only one box you can check?
[LanX]: no two boxes , enemies of the state are just denounced
[LanX]: like judges in Britain or the US

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2017-03-27 12:18 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (320 votes). Check out past polls.