我在Perl中有以下数据序列:
143:0.0209090909090909
270:0.0909090909090909
32:0.0779090909090909
326:0.3009090909090909请问,我如何根据冒号之前的数字对它们进行排序,以将其作为我的输出?
32:0.0779090909090909
143:0.0209090909090909
270:0.0909090909090909
326:0.3009090909090909发布于 2011-11-14 09:05:44
那里有冒号并不重要。
Perl将字符串转换为数字的规则将做正确的事情:
#!/usr/bin/perl
use warnings;
use strict;
my @nums = qw(
143:0.0209090909090909
270:0.0909090909090909
32:0.0779090909090909
326:0.3009090909090909
);
{ no warnings 'numeric';
@nums = sort {$a <=> $b} @nums;
}
print "$_\n" for @nums;发布于 2011-11-14 08:36:11
可以使用内置的sort函数:
程序
#!/usr/bin/env perl
use strict;
use warnings;
my @data = qw(
143:0.0209090909090909
270:0.0909090909090909
32:0.0779090909090909
326:0.3009090909090909
);
my $match = qr/^(\d+):/;
@data = sort { ( $a =~ $match )[0] <=> ( $b =~ $match )[0] } @data;
print join( "\n", @data ), "\n";输出
32:0.0779090909090909
143:0.0209090909090909
270:0.0909090909090909
326:0.3009090909090909发布于 2011-11-14 08:26:56
我会简单地使用
sort -n < input.txt否则:
use strict;
use warnings;
my @lines = (<>);
print for sort {
my @aa = split(/:/, $a);
my @bb = split(/:/, $b);
1*$aa[0] <=> 1*$bb[0]
} @lines;https://stackoverflow.com/questions/8115955
复制相似问题