2010-03-25 57 views
1
@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, 
    }, 
    ); 

我想在每個數組索引散列基於值相反的順序進行排序..如何在Perl中維護排序後的散列?

@sorted =排序{...........請填寫此..... .....} @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, 
}, 
); 

請幫助..謝謝.. 再次陳述了我的請求:我只希望在每個數組索引哈希值由值進行排序..我不想要的數組進行排序..

+0

這功課嗎? – Ether 2010-03-25 14:52:32

回答

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

哈希沒有特定的順序。你應該使用數組來維護順序。

-1

試試這個東西....

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

'%new'會破壞重複的值。 – mob 2010-03-25 14:32:20

0

您可以使用來完成。但我寧願考慮審查我的數據結構。如果您提供了有關您的結構中要存儲的數據類型的更多信息,而不僅僅是簡單的數字,則可以針對您的問題獲得更好的答案。

#!/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"; 
    } 
} 
相關問題