在寻找一些指针时,关于如何按多个值对哈希数组进行排序,我遇到了以下解决方案: Sorting array of hash by multiple keys
但是,似乎无法找到一种动态执行此操作的方法。
比如说,一个人想要排序的参数(这里是:哈希键)的数量取决于用户输入。
使用相同的示例,如用户在链接问题中使用的那样:
$arr_ref = [ { 'brand' => 'A',
'supplier' => 'X',
'PO' => '2'
},
{ 'brand' => 'B',
'supplier' => 'Y',
'PO' => '1'
},
{ 'brand' => 'B',
'supplier' => 'X',
'PO' => '2'
},
{ 'brand' => 'A',
'supplier' => 'X',
'PO' => '1'
},
{ 'brand' => 'B',
'supplier' => 'X',
'PO' => '1'
}
];
用户可以通过“品牌”,“品牌”和“供应商”或其他三个来提供是否要对其进行排序。
答案 0 :(得分:7)
创建一个进行排序的子程序。它接受任意数量的键来进行比较:
use strict;
use warnings;
my @array = (
{ 'brand' => 'A', 'supplier' => 'X', 'PO' => '2' },
{ 'brand' => 'B', 'supplier' => 'Y', 'PO' => '1' },
{ 'brand' => 'B', 'supplier' => 'X', 'PO' => '2' },
{ 'brand' => 'A', 'supplier' => 'X', 'PO' => '1' },
{ 'brand' => 'B', 'supplier' => 'X', 'PO' => '1' },
);
sub custom_sort {
my ($x, $y, @keys) = @_;
for (@keys) {
my $cmp = $x->{$_} cmp $y->{$_};
return $cmp if $cmp;
}
return 0;
}
my @sorted = sort {custom_sort($a, $b, 'brand', 'supplier', 'PO')} @array;
use Data::Dump;
dd @sorted;
输出:
(
{ brand => "A", PO => 1, supplier => "X" },
{ brand => "A", PO => 2, supplier => "X" },
{ brand => "B", PO => 1, supplier => "X" },
{ brand => "B", PO => 2, supplier => "X" },
{ brand => "B", PO => 1, supplier => "Y" },
)