如何索引哈希

use*_*803 3 perl hash

可能重复:
根据插入顺序迭代哈希值?

即时尝试获取此哈希的第五个元素

%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");
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它将是"bee Gees","仅限一晚"

但是当我试图实现这个代码

while (($key, $value) = each %cds) {
   print "$key $value\n";
 }
Run Code Online (Sandbox Code Playgroud)

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

这怎么可能以及如何获得第五个元素?

Joh*_*136 5

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