无法理解Perl哈希排序的行为

时间:2015-01-10 17:44:30

标签: perl perl-data-structures

我是Perl的初学者,我试图从“Beginning Perl:Curtis Poe”中运行这个示例示例

#!/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''apap slices'。

请帮助我理解。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:6)

perldoc perldata

  

哈希是由它们索引的标量值的无序集合   相关的字符串键。

您可以根据需要sort键或值。

答案 2 :(得分:1)

我认为关键是:

my @cheese_tray = values %snacks

来自[1]:http://perldoc.perl.org/functions/values.html “散列条目以明显随机的顺序返回。实际的随机顺序特定于给定的散列;两个散列上完全相同的操作系列可能导致每个散列的顺序不同。”