【问题标题】:Iterate through Array of Hashes in a Hash in Perl在 Perl 的哈希中遍历哈希数组
【发布时间】:2012-08-22 17:53:24
【问题描述】:

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

$VAR1 = {
          'file' => [
                      {
                        'pathname' => './out.log',
                        'size' => '51',
                        'name' => 'out.log',
                        'time' => '1345799296'
                      },
                      {
                        'pathname' => './test.pl',
                        'size' => '2431',
                        'name' => 'test.pl',
                        'time' => '1346080709'
                      },
                      {
                        'pathname' => './foo/bat.txt',
                        'size' => '24',
                        'name' => 'bat.txt',
                        'time' => '1345708287'
                      },
                      {
                        'pathname' => './foo/out.log',
                        'size' => '75',
                        'name' => 'out.log',
                        'time' => '1346063384'
                      }
                    ]
        };

如何循环遍历这些“文件条目”并访问其值?复制my @array = @{ $filelist{file} }; 是否更容易,所以我只有一个哈希数组?

【问题讨论】:

    标签: arrays perl loops hash


    【解决方案1】:

    Perl 中没有哈希数组,只有标量数组。仅当这些标量是对数组或哈希的引用时,才会出现一堆语法糖。

    在您的示例中, $VAR1 保存对哈希的引用,其中包含对包含哈希引用的数组的引用。是的,有很多嵌套需要处理。另外,外部散列似乎有点没用,因为它只包含一个值。所以是的,我认为给内部数组一个有意义的名字肯定会让事情更清楚。它实际上不是“副本”:仅复制了引用,而不是内容。以下所有内容都是等效的:

    my @files = $VAR1 -> {file} # dereferencing with the -> operator
    my @files = ${$VAR1}{file}  # derefencing with the sigil{ref} syntax
    my @files = $$VAR1{file}    # same as above with syntactic sugar
    

    请注意,当使用 sigil{ref} 语法时,sigil 遵循与往常相同的规则:%{$ref}(或 %$ref)是 $ref 引用的哈希,但 %{$ref} 的元素对于给定key${$ref}{key}(或 $$ref{key})。大括号可以包含返回引用的任意代码,而短版本只能在标量变量已经持有引用时使用。

    一旦你的哈希引用数组在一个变量中,迭代它就像:

    for (@files) {
        my %file = %$_;
        # do stuff with %file
    }
    

    见:http://perldoc.perl.org/perlref.html

    【讨论】:

      【解决方案2】:

      无需复制:

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

      【讨论】:

      • 仅供参考,如果您使用 xml::simple xmlin 获取哈希值,则必须使用 foreach my $file (@{ $filelist->{file} })
      • $filelist 定义在哪里?
      • 我必须使用... (@{ $filelist->{file} }) { 才能工作。即取消引用“->”。
      猜你喜欢
      • 1970-01-01
      • 2011-10-28
      • 2013-11-10
      • 2022-07-21
      • 2019-01-13
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多