如何索引哈希

时间:2012-02-07 04:20:34

标签: perl hash

  

可能重复:
  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";
 }

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

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

4 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:4)

一个选项是保持您的哈希原样(无序集合)并使用一组键(一个有序序列)进行扩充。然后遍历数组(按插入顺序)并使用哈希查找相应的值。

另一种选择是从CPAN下载有序的哈希实现:Tie::Hash::Indexed

希望这会有所帮助:-)

答案 2 :(得分:2)

@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"],
);

这是一个数组数组。 $ cd [4] [0]是艺术家,$ cd [4] [1]是标题。

答案 3 :(得分:1)

线索在短语“但不按顺序”。哈希不是有序集合。如果您想按顺序使用它们,请使用有序集合,即数组。完成工作的例子:

#!/usr/bin/perl

use strict;
use warnings;

my @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'    ],
);

for my $cd (@cds) {
    my ($key, $value) = @$cd;

    print "$key $value\n";
}

my $fifth_element = $cds[4];

print "Fifth element is @$fifth_element\n";
相关问题