如何在Perl中维护已排序的哈希?

时间:2010-03-25 09:20:30

标签: perl sorting arrays hash

 @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,
    },
    );

我希望每个数组索引中的哈希值按照相反的顺序排序。

@sorted = sort {...........请填写这个..........} @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,
},
);

请帮忙..先谢谢.. 再次陈述我的请求:我只希望每个数组索引中的哈希值按值排序..我不希望对数组进行排序..

4 个答案:

答案 0 :(得分:1)

哈希没有特定的订单。你应该使用数组来维持秩序。

答案 1 :(得分:1)

Perl哈希没有订单。您必须将它们切换到数组,或者在使用时对它们进行排序(例如,当您需要迭代该哈希时)。

第一个解决方案可能如下:

@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};
   }
}

答案 2 :(得分:0)

您可以使用Tie::Hash::Sorted执行此操作。但我宁愿考虑审查我的数据结构。如果您提供了有关您要在结构中存储哪种数据的更多信息,而不仅仅是简单的数字,那么您可以更好地回答真正的问题。

#!/usr/bin/perl
use strict;
use warnings;

use Tie::Hash::Sorted;

my @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,
    },
);

my @sorted = map {
        tie my %h, 'Tie::Hash::Sorted',
            Hash => { %$_ },
            Sort_Routine => sub {
                    [ sort { $_[0]{$a} <=> $_[0]{$b} } keys %{$_[0]} ]
                };
        \%h;
    } @aoh;

# output data
foreach my $elem (@sorted) {
    print "elem\n";
    while (my ($k, $v) = each %$elem) {
        print "    $k => $v\n";
    }
}

答案 3 :(得分:-1)

试试这个......

foreach $hash ( @aoh)
    {
            my %new  = reverse (%{$hash});
            foreach ( sort {$a <=> $b } keys (%new ))
            {
                    print " $new{$_} :$_ \n ";
            }
            print "-------------\n";
    }