Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

sorting numerically and alphabetically

by kepster (Initiate)
on Jun 28, 2006 at 12:28 UTC ( #557993=perlquestion: print w/ replies, xml ) Need Help??
kepster has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I've got a program that needs a list of filenames sorted, filenames are e.g. firstcase_1, secondcase_3. The query is how can I sort alphabetically & then numerically to get e.g.
firstcase_1
firstcase_2
firstcase_3
secondcase_4
I'm sure it's relatively simple but I can't find an example, any help appreciated...

Comment on sorting numerically and alphabetically
Re: sorting numerically and alphabetically
by Corion (Pope) on Jun 28, 2006 at 12:34 UTC

    For your limited example, sort already does exactly what you want. I guess though that what you want isn't what sort does for the following example:

    firstcase_1 secondcase_4 secondcase_11 secondcase_012

    What you want is called "natural sorting", and tye has a nice node on it - our categorized Questions and Answers also has How do I do a natural sort on an array?.

Re: sorting numerically and alphabetically
by cLive ;-) (Parson) on Jun 28, 2006 at 18:26 UTC
    Break up the elements and sort on the two fragments:
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper 'Dumper'; my @files = qw(firstcase_1 firstcase_2 firstcase_10 secondcase_4 secon +dcase_1 secondcase_11); my @sorted = sort { $a =~ /^(\w+)_(\d+)$/; my ($a1,$a2) = ($1,$2); $b =~ /^(\w+)_(\d+)$/; my ($b1,$b2) = ($1,$2); $a1 cmp $b1 || $a2 <=> $b2 } @files; print Dumper(\@sorted);
Re: sorting numerically and alphabetically
by Anonymous Monk on Jun 29, 2006 at 15:16 UTC
    Use Sort::Naturally. Just use:
    use Sort::Naturally; @list = nsort(qw( foo12a foo12z foo13a foo 14 9x foo12 fooa foolio Foolio Foo12a )); print join(' ', @list), "\n";
      or Sort::Key::Natural that is much faster...
      use Sort::Key::Natural qw(natsort); @sorted = natsort qw(foo12a foo12z foo13a foo 14 9x foo12 fooa foolio +Foolio Foo12a);

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2015-07-05 18:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (67 votes), past polls