http://www.perlmonks.org?node_id=557993

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...

Replies are listed 'Best First'.
Re: sorting numerically and alphabetically
by Corion (Patriarch) 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 ;-) (Prior) 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);