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

Re: Sorting a File which contains numbers

by valavanp (Curate)
on Oct 30, 2006 at 13:24 UTC ( #581282=note: print w/ replies, xml ) Need Help??


in reply to Sorting a File which contains numbers

You can try this:

use strict; use warnings; my @a=(1,5,2,4); print "Ascending order:"; print sort(@a); print "\n"; print "Descending order:"; print reverse sort(@a);


Comment on Re: Sorting a File which contains numbers
Download Code
Re^2: Sorting a File which contains numbers
by johngg (Abbot) on Oct 30, 2006 at 14:50 UTC
    Your solution is going to fail as soon as you encounter numbers that are more than single-digits because the default sort that you use is lexical, not numeric. Consider

    perl -le '@arr = (2, 17, 8, 5, 26); print for sort @arr;'

    produces

    17 2 26 5 8

    whereas

    perl -le '@arr = (2, 17, 8, 5, 26); print for sort {$a <=> $b} @arr;'

    does a numerical sort and produces

    2 5 8 17 26

    To sort descending numerically change the anonymous sort routine to {$b <=> $a} rather than using reverse.

    Cheers,

    JohnGG

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2014-08-30 10:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (293 votes), past polls