在Perl中对字符串+数字进行排序

时间:2014-02-23 20:10:43

标签: perl sorting

我有一个包含这些值的数组:

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

我该怎么办?

2 个答案:

答案 0 :(得分:4)

您可以使用<=>

隔离数字,并对它们进行比较/排序numerically
@arr = map $_->[0], sort{ $a->[1] <=> $b->[1] } map [ $_, /(\d+)/ ], @arr;

答案 1 :(得分: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