【问题标题】:How to iterate through Array of Hashes in a Hash in Perl如何在 Perl 中遍历哈希中的哈希数组
【发布时间】:2014-03-02 04:55:04
【问题描述】:

我有一个哈希数组,看起来像这样:

$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 新手,请在回复中提供详细信息。

【问题讨论】:

  • $var 是对散列的引用,该散列的元素之一(迄今为止唯一的一个)是 items 数组。除了items 之外,您还需要在该哈希中包含任何其他元素吗?

标签: perl hash


【解决方案1】:

Perl's Data Structures Cookbook 是您正在处理的数据结构的绝佳参考。

也就是说,这里是代码:

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

【讨论】:

    【解决方案2】:

    首先是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 上使用 @{} 时,即 @{ $filelist{file} },这将转换或扩展为数组。

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

    请注意,当你使用$hashrefname->{$key}时,表示hashref访问key, $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}
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-22
      • 2011-10-28
      • 2022-07-21
      • 2013-11-10
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      相关资源
      最近更新 更多