我是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'。
请帮助我理解。
答案 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)
答案 2 :(得分:1)
我认为关键是:
my @cheese_tray = values %snacks
来自[1]:http://perldoc.perl.org/functions/values.html “散列条目以明显随机的顺序返回。实际的随机顺序特定于给定的散列;两个散列上完全相同的操作系列可能导致每个散列的顺序不同。”