Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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);

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;'


    17 2 26 5 8


    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.



Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://581282]
[1nickt]: Corion HPs? ugh. I was impressed with Lenovo's gaming laptops; if it weren't for the red backlighting and general flashiness of the aesthetic, I might have gone with that. But all that was until I discovered that the Dell Precision line is still around.
[1nickt]: stevieb I don;t doubt that there's a difference. BestBuy has "consumer" models only on display.

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (15)
As of 2017-03-27 13:39 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (320 votes). Check out past polls.