无法理解 Perl 散列排序的行为

Unable to understand the behaviour of Perl hash ordering

我是 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";

以上代码的输出,当我在 windows7 系统上尝试使用 ActivePerl 和 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''soap slices'。

请帮我理解。

哈希未排序。如果你想要一个特定的顺序,你需要使用一个数组。

例如:

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

现在您拥有 @type 中的类型。

你当然也可以使用sort:

my @type = sort keys %snacks;

perldoc perldata:

Hashes are unordered collections of scalar values indexed by their associated string key.

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

我认为关键是:

my @cheese_tray = values %snacks

来自 [1]:http://perldoc.perl.org/functions/values.html "Hash entries are returned in an apparently random order. The actual random order is specific to a given hash; the exact same series of operations on two hashes may result in a different order for each hash."