2015-01-10 12 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 “散列条目在一个明显随机的顺序返回的实际随机顺序是针对特定的哈希值;完全相同的系列对两个散列的操作可能会导致每个散列的顺序不同。“