Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
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
Replies are listed 'Best First'.
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 pondering the Monastery: (12)
As of 2015-07-31 10:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (276 votes), past polls