Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Answer: How do I do a natural sort on an array?

( #68205=categorized answer: print w/ replies, xml ) Need Help??

Q&A > sorting > How do I do a natural sort on an array? contributed by tye

my @sorted= grep {s/(^|\D)0+(\d)/$1$2/g,1} sort grep {s/(\d+)/sprintf"%06.6d",$1/ge,1} @data;
See RE: RE: Re: Sorting on Section Numbers some important style comments.

Features and limitations:

  • Strips extra leading zeros from digit strings
  • Doesn't handle floating point numbers at all well
  • Sorts negative integers in reverse after positive integers
  • Uses very little extra memory
  • You must specify the maximum number of digits your integers will have (6 in the above code)

Comment on Answer: How do I do a natural sort on an array?
Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (10)
As of 2014-09-30 19:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (382 votes), past polls