Possible Duplicate:
Iterating hash based on the insertion order?




我试图获取此哈希的第五个元素

%cds = ("Dr. Hook"         => "Sylvias Mother",
        "Rod Stewart"    => "Maggie May",
        "Andrea Bocelli"  => "Romanza",
        "Kenny Rogers"  => "For the good times",
        "Bee Gees"        => "One night only",
        "Bonnie Tyler"    => "Hide your heart");


在这种情况下,它将是“ bee Gees”,“仅一晚”

但是当我试图实现此代码时

while (($key, $value) = each %cds) {
   print "$key $value\n";
 }


这会打印所有元素,但不是按顺序打印

这怎么可能?我如何获得第五个要素?

最佳答案

哈希没有以任何(用户敏感的)顺序存储。
如果需要通过数字索引获取项目,则不应该使用哈希。
您可以对键的集合进行排序(仍然不会得到“插入顺序”)。

10-07 19:18
查看更多