我想根据逗号后的值对这个数组进行排序
my @coords;
$coords[0] = "33.7645539, -84.3585973";
$coords[1] = "33.7683870, -84.3559850";
$coords[2] = "33.7687753, -84.3541355";
foreach my $coord (@sorted_coords) {
print "$coord\n";
}
输出:
33.7687753, -84.3541355
33.7683870, -84.3559850
33.7645539, -84.3585973
我曾考虑使用 map、grep 和捕获组作为
sort
的列表输入,但我还没有走多远:my @sorted_coords = sort { $a <=> $b } map {$_ =~ /, (-*\d+\.\d+)/} @unique_coords;
最佳答案
很容易屈服于使用花哨的实现而不是简单明了的实现的诱惑。除非数据集很大,否则使用转换的速度优势可以忽略不计,代价是易读性大大降低
这里只需要一个标准的排序块
use strict;
use warnings;
my @coords = (
"33.7645539, -84.3585973",
"33.7683870, -84.3559850",
"33.7687753, -84.3541355",
);
my @sorted_coords = sort {
my ($aa, $bb) = map { (split)[1] } $a, $b;
$bb <=> $aa;
} @coords;
print "$_\n" for @sorted_coords;
输出
33.7687753, -84.3541355
33.7683870, -84.3559850
33.7645539, -84.3585973
更新
如果您愿意,可以使用正则表达式从输入记录中提取第二个字段。更换
map
像这样的声明my ($aa, $bb) = map /.*(\S+)/, $a, $b;
会正常工作
关于Perl 按模式匹配对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31909163/