我怎样才能保持Perl中的排序的散列? [英] How can I maintain a sorted hash in Perl?

查看:82
本文介绍了我怎样才能保持Perl中的排序的散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 @aoh =(
     {
        3 => 15,
        4 => 8,
        5 => 9,
     },
     {
        3 => 11,
        4 => 25,
        5 => 6,
     },
    {
        3 => 5,
        4 => 18,
        5 => 5,
    },
    {
        0 => 16,
        1 => 11,
        2 => 7,
    },
    {
        0 => 21,
        1 => 13,
        2 => 31,
     },
    {
        0 => 11,
        1 => 14,
        2 => 31,
    },
    );

我要在基于价值观相反的顺序排列每个数组索引的哈希值。

I want the hashes in each array index sorted in reverse order based on values..

@sorted = {排序请...........填补这一..........} @aoh;

@sorted = sort { ........... please fill this..........} @aoh;

期望的输出

@aoh =(
 {
    4 => 8,
    5 => 9,
    3 => 15,
 },
 {
    5 => 6,
    3 => 11,
    4 => 25,
},
{
    5 => 5,
    3 => 5,
    4 => 18,
},
{
     2 => 7,
     1 => 11,
     0 => 16,
},
{
    1 => 13,
    0 => 21,
    2 => 31,
 },
{
    0 => 11,
    1 => 14,
    2 => 31,
},
);

请帮助..在此先感谢..
再次说明我的要求:我只希望在每个数组索引哈希值由值进行排序..我不希望要排序的数组。

Please help.. Thanks in advance.. Stating my request again: I only want the hashes in each array index to be sorted by values.. i dont want the array to be sorted..

推荐答案

Perl的哈希值没有秩序。您必须将它们切换到阵列,或(当你需要遍历散列例如)在他们使用排序。

Perl hashes do not have order. You must either switch them to arrays, or sort them upon usage (e.g. when you need to iterate over that hash).

第一种解决方案可能看起来像:

The first solution could look like:

@aoh =(
 [{ 4 => 8 }
, { 5 => 9 },
, { 3 => 15 }
 ],

...

第二个解决方案是:

foreach $subhash (@aoh) {
   foreach $sorted_key (sort { $subhash->{$a} <=> $subhash->{$b} } keys %$subhash) {
      # Do something with $subhash->{$sorted_key};
   }
}

这篇关于我怎样才能保持Perl中的排序的散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆