【问题标题】:Sorting an array of hashes, based on the value of a particular key within each hash in perl根据 perl 中每个散列中特定键的值对散列数组进行排序
【发布时间】:2014-11-07 13:39:33
【问题描述】:

我已经进行了一些搜索,并努力找到了这个问题的答案。

假设我有一个这样的哈希数组..

my @AoH = (
    {   'ip_type'     => 1,
        'ip_ref'      => 0001,
        'ip_address'  => '192.168.0.1',
        'ip_priority' => '100'
    },
    {   'ip_type'     => 1,
        'ip_ref'      => 0002,
        'ip_address'  => '192.168.0.2',
        'ip_priority' => '1'
    }
);

在上下文中,这些是多个 IP 地址,我打算在其中进行负载平衡。 'ip_priority' 值决定了哪个是第一个,然后是第二个。主要和备份,基本上。

但是,我想根据散列中的 ip 优先级值对数组元素(也称为散列)进行数字排序。

所以,上面的 AoH 最好是……

my @AoH = (
    {   'ip_type'     => 1,
        'ip_ref'      => 0002,
        'ip_address'  => '192.168.0.2',
        'ip_priority' => '1'
    },
    {   'ip_type'     => 1,
        'ip_ref'      => 0001,
        'ip_address'  => '192.168.0.1',
        'ip_priority' => '100'
    }
);

所以$AoH[0]->{ip_priority} 现在包含 1,$AoH[1]->{ip_priority} 包含 100。

如何执行排序以实现上面的第二个示例?我正在努力寻找一个可行的例子!

【问题讨论】:

    标签: arrays perl data-structures hash


    【解决方案1】:

    你可以使用:

    my @sorted = sort {$a->{ip_priority} <=> $b->{ip_priority}} @AoH;
    

    【讨论】:

    • achhh...我尝试了这样的事情。也许我有一个错字。谢谢你的朋友,它工作得很好。
    猜你喜欢
    • 1970-01-01
    • 2015-01-26
    • 2014-05-19
    • 1970-01-01
    • 2014-05-07
    • 2011-12-13
    • 2021-02-04
    • 2014-01-08
    • 2015-02-03
    相关资源
    最近更新 更多