Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Answer: How do I sort something alphabetically?

by arturo (Vicar)
on Nov 06, 2000 at 21:29 UTC ( #40193=categorized answer: print w/replies, xml ) Need Help??

Q&A > sorting > How do I sort something alphabetically? - Answer contributed by arturo

The default sort behavior with strings is "ASCIIbetical," rather than alphabetical. ASCII-wise, the capital letters (as a group) come before the lowercase (as a group); thus "D" comes before "a."

So assuming you want to sort a list of words, what you want is:

# make it a "sort sub" sub alphabetical { # compares lower-cased versions of the strings lc($a) cmp lc($b); } # to sort having defined this sub, you do @list = sort alphabetical @list;

Or, to avoid making a bunch of tiny little otherwise useless functions, sort also lets you use a block in place of a function:

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

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (1)
As of 2018-05-26 00:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?