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

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.
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 (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 ;-) (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);

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://557993]
Approved by marto
Front-paged by tye
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2017-07-21 18:55 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (334 votes). Check out past polls.