gpt4 book ai didi

arrays - 对具有字母数字值的哈希数组进行排序

转载 作者:行者123 更新时间:2023-12-01 23:55:05 25 4
gpt4 key购买 nike

我在对哈希数组进行排序时遇到问题;具有我需要排序的字母数字值的哈希。

引用这个question !我的问题是这个问题的延伸。我尝试了上述问题的解决方案,但没有得到所需的输出。

$arr_ref = [
{ brand => "A.1", PO => "1.a", supplier => "X" },
{ brand => "A.2", PO => "2.a", supplier => "X" },
{ brand => "B.1", PO => "1.b", supplier => "X" },
{ brand => "B.2", PO => "2.b", supplier => "X" },
{ brand => "B.3", PO => "1.c", supplier => "Y" },
]

我需要按品牌或采购订单排序。

#sort the array reference and place the array back into the standard_set
$arr_ref = [sort by_brand @$arr_ref];
sub by_brand {
$a->{brand} cmp $b->{brand}
}

复杂性是关键;可以以数字或字母字符开头。品牌或 PO 也可以有不同的大小。分隔符可以是点或连字符。

我们能否根据 $arr_ref 中收到的输入来解决这个问题?

最佳答案

你们真的很亲密。您只需删除 [] 括号并取消引用要分配给 @$array_ref = ... 的数组。

use strict;
use warnings;

my $arr_ref = [
{ brand => "B.3", PO => "1.c", supplier => "Y" },
{ brand => "B.2", PO => "2.b", supplier => "X" },
{ brand => "B.1", PO => "1.b", supplier => "X" },
{ brand => "A.2", PO => "2.a", supplier => "X" },
{ brand => "A.1", PO => "1.a", supplier => "X" },
];

my @sorted = sort { $a->{brand} cmp $b->{brand} } @$arr_ref;

use Data::Dump;
dd @sorted;

输出:

(
{ brand => "A.1", PO => "1.a", supplier => "X" },
{ brand => "A.2", PO => "2.a", supplier => "X" },
{ brand => "B.1", PO => "1.b", supplier => "X" },
{ brand => "B.2", PO => "2.b", supplier => "X" },
{ brand => "B.3", PO => "1.c", supplier => "Y" },
)

关于arrays - 对具有字母数字值的哈希数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24199190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com