CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
need to print numbers in order

 



regex2012
User

Jun 5, 2015, 10:40 AM

Post #1 of 2 (998 views)
need to print numbers in order Can't Post

I have a list of numbers:
@list =qw(7 71 70 8 50);
I am using the following statement to compare them:

Code
@list = sort{(lc($a) cmp lc($b)} @list;

This gives the following

5
7
70
71
8

I was told that I could use expand to help with this. Is this true? Is perl seeing these numbers as single digit and sorting them accordingly? Is there a way to make them print in order without an expand subroutine?


aaron_baugher
Novice

Jun 5, 2015, 3:47 PM

Post #2 of 2 (993 views)
Re: [regex2012] need to print numbers in order [In reply to] Can't Post

The 'cmp' function does a string comparison, so '50' is sorted before '7'. To do numeric comparison, use <=> . See 'perldoc -q sort' for more examples of ways to sort.

There's also no need for lc() here, since you can't lowercase a number.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives