2012-11-08 132 views
4

我有下面的散列,我希望保持它在我設置的順序;這甚至有可能嗎?如果沒有,有沒有其他的選擇?排序從第一個鍵到最後一個(Perl)的散列

my %hash = ('Key1' => 'Value1', 'Key2' => 'Value2', 'Key3' => 'Value3'); 

是否需要編寫自定義排序子程序?我有什麼選擇?

謝謝!

+2

不,數組也不保留插入順序。 '$ A [1] = 「A」; $ A [0] = 「B」;打印「@a \ n」;'打印'b a'。數組和哈希按照物理順序返回元素。 – ikegami

+0

爲什麼你需要排序關聯數組(散列)? – gaussblurinc

回答

8

http://metacpan.org/pod/Tie::IxHash

use Tie::IxHash; 
my %hash; 
tie %hash,'Tie::IxHash'; 

該散列將維持其秩序。

+0

我希望有一些不需要外部庫的東西,但是,無論如何,這應該會訣竅。 經過測試和工作,謝謝! – user1807879

1

嘗試這樣做:

print "$_=$hash{$_}\n" for sort keys %hash; 

,如果你想它排序按字母順序排列。

如果您需要保留原始訂單,請參閱其他帖子。

http://perldoc.perl.org/functions/sort.html

2

參見Tie::Hash::Indexed。引用其內容摘要:

use Tie::Hash::Indexed; 

tie my %hash, 'Tie::Hash::Indexed'; 

%hash = (I => 1, n => 2, d => 3, e => 4); 
$hash{x} = 5; 

print keys %hash, "\n"; # prints 'Index' 
print values %hash, "\n"; # prints '12345' 
1

一種可能性是按照您有時用數組進行的操作:指定鍵。

for (0..$#a) { # Sorted array keys 
    say $a[$_]; 
} 

for (sort keys %h) { # Sorted hash keys 
    say $h{$_}; 
} 

for (0, 1, 3) { # Sorted array keys 
    say $h{$_}; 
} 

for (qw(Key1 Key2 Key3)) { # Sorted hash keys 
    say $h{$_}; 
} 

您也可以按照如下取有序值:

my @values = @h{qw(Key1 Key2 Key3)}; 
0

這取決於你將如何訪問數據。如果你只是想存儲它們並訪問最後的/第一個值,你總是可以把哈希放入一個數組中並使用push()和pop()。

#!/usr/bin/env perl 

use strict; 
use warnings; 

use v5.10; 

use Data::Dumper; 

my @hashes; 

foreach(1..5){ 
    push @hashes, { "key $_" => "foo" }; 
} 


say Dumper(\@hashes); 
相關問題