0

I have an array(@pssm_list) which contains files like this

1.nr.pssm
2.nr.pssm
3.nr.pssm
4.nr.pssm
5.nr.pssm
6.nr.pssm
7.nr.pssm

the name of file list is 1.nr.pssm to 226.nr.pssm

I try to use sort(@pssm_list) , but the order is not from 1 to 226

so I try to write the code like this

opendir(pssm_handle,$ARGV[0]);
@pssm_list = grep(/\.pssm/,readdir(pssm_handle));

$tag = 0;
until($tag > 226)
{
        foreach $file (@pssm_list)
        {
                @Temp = split("[.]",$file);
                if($Temp[0] == $tag)
                {
                        push(@Sorted,join("",$file));
                }
        }
        $tag++;
}

I want to know does there exists any solution can sort the list in one line?

3 Answers 3

5

I hit upon this problem as well, and I used this package called Sort::Naturally to help me sort the numbers correctly.

Under natural sorting, numeric substrings are compared numerically, and other word-characters are compared lexically.

3
my @pssm_list = 
  map $_->[0],
  sort { $a->[1] <=> $b->[1] }
  map [ $_, /(\d+)/ ],
  grep(/\.pssm/,readdir(pssm_handle));

or slightly less efficient sort:

my @pssm_list =
  sort { 
    my ($x,$y) = map /(\d+)/, ($a,$b); 
    $x <=> $y;
  }
  grep(/\.pssm/,readdir(pssm_handle));
3

I think this should do it:

@Sorted = sort { int( $a ) <=> int( $b ) } @pssm_list;

This relies on the forgiving nature of int() whereby e.g. int( "99xyz" ) == 99.

If your filenames were more complex, you should replace int( $a ) with a function call that extracts the numeric part, or use map as suggested by mpapec.

Edit: My first attempt was way off, sorry, been working in Ruby far too long to remember the correct Perl syntax!

2
  • ruby needs explicit $a and $b, and that seems to be only difference
    – mpapec
    Aug 13, 2013 at 8:44
  • @mpapec: In Ruby, you would generally do pssm_list.sort_by { |item| item.method }, and item.method would return an enumerable object with well-defined sort behaviour. Yes, it is also possible to use Perl-like syntax, but I haven't seen that much. Aug 13, 2013 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.