2013-10-25 46 views
4

如何打印散列元素的鍵/值對按照散列元素的添加順序排列。如何按散列元素的順序添加散列元素

例如:

%hash = ("a", "1", "b", "2", "c", "3"); 
while (($key, $value) = each %hash) { 
    print "$key", "$value\n"; 
} 

以上結果如下:

c3 
a1 
b2 

我正在尋找一種方式來打印如下:提前

a1 
b2 
c3 

謝謝!

回答

4

既然你不想使用所提到的任何模塊(領帶:: IxHash和Tie ::哈希索引::),自此散列unordered collections(如前說的),你必須存儲這個信息在插入值:

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

my %hash; 
my %index; #keep track of the insertion order 
my $i=0; 
for (["a","1"], ["b","2"], ["c","3"]) { #caveat: you can't insert values in your hash as you did before in one line 
    $index{$_->[0]}=$i++; 
    $hash{$_->[0]}=$_->[1]; 
} 

for (sort {$index{$a}<=>$index{$b}} keys %hash) { #caveat: you can't use while anymore since you need to sort 
    print "$_$hash{$_}\n"; 
} 

這將打印:

a1 
b2 
c3 
5

散列沒有排序。您需要選擇另一個數據結構。

+0

不知道這一點,謝謝。將不得不找到一個解決方法然後:) –

5

你需要有序哈希Tie::IxHash模塊,

use Tie::IxHash; 

tie(my %hash, 'Tie::IxHash'); 
%hash = ("a", "1", "b", "2", "c", "3"); 

while (my ($key, $value) = each %hash) { 
    print "$key", "$value\n"; 
} 
5

散列一般是無序的。您可以改爲使用有序散列。嘗試CPAN的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' 
+0

這確實工作,但是,我試圖不包括模塊。 必須找到另一種方式來解決這個問題。 感謝您的幫助,雖然:) –

8

你怎麼打印一個哈希的鍵/值對,在它們出現在哈希的順序。

您使用的代碼確實如此。 c3,a1,b2是當時元素出現在hash中的順序。

你實際上想要按照它們插入的順序打印它們。爲此,您需要跟蹤插入元素的順序,否則您將不得不使用哈希以外的內容,例如前面提到的Tie::IxHashTie::Hash::Indexed

+1

這是現在的首選? –

+3

@mpapec,我從來沒有需要。我總是能夠使用數組或數組+哈希組合。 – ikegami

相關問題