2014-02-23 88 views
0

我與這些值的數組:排序字符串+數字在Perl

scores Parent=mRNA1 
scores Parent=mRNA2 
scores Parent=mRNA3 
scores Parent=mRNA4 
scores Parent=mRNA5 
scores Parent=mRNA6 
scores Parent=mRNA7 
scores Parent=mRNA8 
scores Parent=mRNA9 
scores Parent=mRNA10 
scores Parent=mRNA11 

,但我不能對它們進行排序。通過使用sort { $a cmp $b }對其進行分類,我獲得:

scores Parent=mRNA1 
scores Parent=mRNA10 
scores Parent=mRNA11 
scores Parent=mRNA2 
scores Parent=mRNA3 
scores Parent=mRNA4 
scores Parent=mRNA5 
scores Parent=mRNA6 
scores Parent=mRNA7 
scores Parent=mRNA8 
scores Parent=mRNA9 

我該怎麼辦?

回答

4

您可以隔離數字,比較/排序他們numerically使用<=>

@arr = map $_->[0], sort{ $a->[1] <=> $b->[1] } map [ $_, /(\d+)/ ], @arr; 
+3

僅供參考HTTP: //en.wikipedia.org/wiki/Schwartzian_transform – chilemagic

3

您可以使用Sort::Naturally此:

use strict; 
use warnings; 
use Sort::Naturally; 

chomp(my @arr = <DATA>); 
print "$_\n" for nsort @arr; 

__DATA__ 
scores Parent=mRNA9 
scores Parent=mRNA10 
scores Parent=mRNA11 
scores Parent=mRNA1 
scores Parent=mRNA2 
scores Parent=mRNA3 
scores Parent=mRNA4 
scores Parent=mRNA8 
scores Parent=mRNA5 
scores Parent=mRNA6 
scores Parent=mRNA7 

輸出:

scores Parent=mRNA1 
scores Parent=mRNA2 
scores Parent=mRNA3 
scores Parent=mRNA4 
scores Parent=mRNA5 
scores Parent=mRNA6 
scores Parent=mRNA7 
scores Parent=mRNA8 
scores Parent=mRNA9 
scores Parent=mRNA10 
scores Parent=mRNA11