如何在Perl中的哈希中迭代哈希数组

时间:2014-03-02 04:55:05

标签: perl hash

我在哈希中有一个哈希数组,如下所示:

$var  = {
      'items' => [
                      {
                        'name'  => 'name1',
                        'type'  => 'type1',
                        'width' => 'width1',
                      },
                      {
                        'name'  => 'name2',
                        'type'  => 'type2',
                        'width' => 'width2',
                      },
                      {
                        'name'  => 'name3',
                        'type'  => 'type3',
                        'width' => 'width3',
                      }                      
                   ]
    };

我编写了以下代码来从文件中获取值。

my @members = ("name"    =>  $name,
               "type"    =>  $type,
               "width"   =>  $width);

$rec->{$items} = [ @members ];

push @var, $rec;

我不确定如何从此数据结构中检索值。

我在Iterate through Array of Hashes in a Hash in Perl中看到了解决方案。 但我不明白。我不确定他们在代码中提到的$ filelist是什么。

foreach my $file (@{ $filelist{file} }) {
    print "path: $file->{pathname}; size: $file->{size}; ...\n";
}

我是perl的新手,请在回复中提供详细信息。

2 个答案:

答案 0 :(得分:2)

对于您正在处理的数据结构的一个很好的参考是Perl's Data Structures Cookbook

那就是说,这是代码:

for my $item (@{$aoh->{items}}) {
    # '@' casts the $aoh->{items} hash references to an array
    print $item->{name};
}

答案 1 :(得分:1)

首先是question中的结构

$VAR1 = {
          'file' => [
                      {
                        'pathname' => './out.log',
                        'size' => '51',
                        'name' => 'out.log',
                        'time' => '1345799296'
                      },
.
.
.
}

实际上是hashref $filelist的打印或输出。 Data::Dumper模块,有助于以正确读取的方式打印hashref,arrayref等结构。

所以$VAR1只是使用Dumper打印$filelist

现在,关于foreach循环迭代值:

foreach my $file (@{ $filelist{file} })

此处,$filelist{file}部分返回数组引用(注意:[]表示arrayref)。

现在,当您在此arrayref @{}上使用@{ $filelist{file} }时,会将其转换或扩展为数组。

一旦我们将arrayref转换为数组类型,我们就可以使用foreach迭代。

请注意,当您使用$hashrefname->{$key}时,这意味着hashref访问密钥, $hashname{$key}表示哈希访问密钥。对于arrayef和数组也是如此,但是在数组的情况下,有些数字代替键。

解决您的问题:

您需要将成员存储为hashref而不是数组,即

my $member = {"name"    =>  $name,
               "type"    =>  $type,
               "width"   =>  $width};

然后你可以推送你从文件中读取的每个hashref(我猜它来自文件) 进入数组

push @arr, $member

然后将arrayref分配给项目

$rec->{items} = \@arr

现在您可以访问值

foreach my $eachhashref (@{$rec->{items}})
{
print $eachhashref->{name}
}