2015-01-10 9 views
1

我在Perl的初學者,我試圖從「開始的Perl:柯蒂斯坡」運行這個樣本例如行爲無法理解Perl散列的訂貨

#!/perl/bin/perl 

use strict; 
use warnings; 
use diagnostics; 

my $hero = 'Ovid'; 
my $fool = $hero; 
print "$hero isn't that much of a hero. $fool is a fool.\n"; 

$hero = 'anybody else'; 
print "$hero is probably more of a hero than $fool.\n"; 

my %snacks = (
    stinky => 'limburger', 
    yummy => 'brie', 
    surprise => 'soap slices', 
); 
my @cheese_tray = values %snacks; 
print "Our cheese tray will have: "; 
for my $cheese (@cheese_tray) { 
    print "'$cheese' "; 
} 
print "\n"; 

上面的代碼的輸出,當我試圖在我的activeperl與Windows7系統和codepad.org

Ovid isn't that much of a hero. Ovid is a fool. 
anybody else is probably more of a hero than Ovid. 
Our cheese tray will have: 'limburger''soap slices''brie' 

我不跟三線清晰,其打印「limburger''soap slices''brie」,但哈希順序是有「limburger''brie」」肥皂片「。

請幫我理解。

回答

6

哈希沒有訂購。如果你想要一個特定的訂單,你需要使用一個數組。

例如:

my @desc = qw(stinky yummy surprise); 
my @type = ("limburger", "brie", "soap slices"); 
my %snacks; 
@snacks{@desc} = @type; 

現在你有類型@type

你當然也可以使用sort

my @type = sort keys %snacks; 
6

perldoc perldata

哈希是由他們的 相關的字符串鍵索引的標量值的無序集合。

您可以根據需要sort鍵或值。

1

我認爲關鍵是:

my @cheese_tray = values %snacks 

從[1]:http://perldoc.perl.org/functions/values.html 「散列條目在一個明顯隨機的順序返回的實際隨機順序是針對特定的哈希值;完全相同的系列對兩個散列的操作可能會導致每個散列的順序不同。「