Perl 按模式匹配对数组进行排序

标签 perl sorting

我想根据逗号后的值对这个数组进行排序

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/

相关文章:

perl - 在 Perl 中格式化 GD::Graph x 轴

regex - 从数组中删除空白元素

mysql - 如何将数组的一部分插入MySQL?

c - 按名称排序结构(双向链表)

Javascript 对象按键自行排序

json - 如何在Perl中捕获 "failed to decode JSON"错误消息?

mysql - 如何检查 mysql dbi Perl 中的重复键?

python - 使用其构造函数初始化 OrderedDict 以使其保留初始数据顺序的正确方法?

c++ - 合并的正确语法

Python:从有序列表中删除不在无序列表中的条目