键/值的分配顺序是什么?

Cha*_*hak 2 perl hash

my %fruit_colors = ("apple", "red", "banana", "yellow");
my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;
print @fruits;            #output is: bananaapple
print "\n";
print @colors;            #output is: yellowred
Run Code Online (Sandbox Code Playgroud)

键盘链接:http://codepad.org/I0wrTPSe

谁能解释一下为什么输出print @fruits;是bananaapple.我以为这将是applebanana.我认为keys哈希%fruit_colors是以@fruits相反的顺序分配给数组,即最后一个元素首先被分配.是吗?

print @colors;为什么黄色而不是红色相同的情况?

Rog*_*ger 10

该顺序是非确定性的,并且取决于可能会发生变化的哈希算法的底层实现.您永远不应该依赖订购,如果您需要排序结果,您应该添加自己的排序.

请参阅此处perl文档


Sin*_*nür 7

请参阅perldoc -f键.perldocPerl附带.在学习语言时,至少要先阅读一些关于语言的内容是有用的:

散列的键以明显随机的顺序返回.实际的随机顺序在未来的Perl版本中可能会发生变化,但保证与值或每个函数产生的顺序相同(假设散列未被修改).从Perl 5.8.1开始,出于安全原因,即使在不同的Perl运行之间,排序也可能不同(请参阅perlsec中的算法复杂性攻击).