Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Sort Array

by Mehdi (Initiate)
on Jun 08, 2001 at 01:33 UTC ( #86763=perlquestion: print w/replies, xml ) Need Help??

Mehdi has asked for the wisdom of the Perl Monks concerning the following question:

when I use sort() to sort an array like this:
@array = (70, 10, 8);
@array = sort (@array);
the result is : 10, 70, 8
how can I get the result as: 8, 10, 70 in Perl?

Replies are listed 'Best First'.
Re: Sort Array
by wog (Curate) on Jun 08, 2001 at 01:35 UTC
    See the documentation for sort:

    # use <=> instead of default cmp @array = sort { $a <=> $b } @array;
Re: Sort Array
by ZZamboni (Curate) on Jun 08, 2001 at 02:02 UTC
    By default sort uses the cmp operator to compare elements, which does a string comparison. In ASCII order, "10" comes before "8", which is why you are getting those results. As wog pointed out, you have to instruct the <=> operator to make it compare things as numbers.

    --ZZamboni

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2020-07-08 04:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?