Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: sorting an array of file names

by bobf (Monsignor)
on Dec 19, 2009 at 16:41 UTC ( #813534=note: print w/replies, xml ) Need Help??

in reply to sorting an array of file names

The default sort order is lexical. If you want a numeric sort, you need to specify a sort routine using the <=> operator (see perlop). See sort for more information.

Since your filenames have both numeric and alpha components, you will probably need to split the pieces apart before doing the comparison. The Schwartzian Transform is good for this kind of thing.

Here is one approach. Extend the sort routine as needed if you want to specify a secondary/etc sort order in the event two filenames start with the same numeric component.

use strict; use warnings; my @files = qw( 9.10.force.0.5.1LGY.pdb 29.30.force.0.5.1LGY.pdb 30.31.force.0.5.1LGY.pdb 31.32.force.0.5.1LGY.pdb 100.101.force.0.5.1LGY.pdb 101.102.force.0.5.1LGY.pdb ); my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, split( /\./, $_ ) ] } @files; print "$_\n" for @sorted;

Love those pdb files. :-) Lipase, huh? Interesting stuff.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://813534]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2017-01-22 19:35 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (189 votes). Check out past polls.