【问题标题】:How do I append a new hash to an array of hashes?如何将新哈希附加到哈希数组?
【发布时间】:2018-01-28 00:12:44
【问题描述】:

如果我想使用循环向mother_hash 中的所有数组添加新哈希,语法是什么?

我的哈希:

my %mother_hash = (
    'daughter_hash1' => [ 
        { 
          'e' => '-4.3', 
          'seq' => 'AGGCACC', 
          'end' => '97', 
          'start' => '81' 
        } 
    ],
    'daughter_hash2' => [ 
        { 
          'e' => '-4.4', 
          'seq' => 'CAGT', 
          'end' => '17', 
          'start' => '6' 
        }, 
        { 
          'e' => '-4.1', 
          'seq' => 'GTT', 
          'end' => '51', 
          'start' => '26' 
        }, 
        { 
          'e' => '-4.1', 
          'seq' => 'TTG', 
          'end' => '53', 
          'start' => '28' 
        } 
    ],
    #...
);

【问题讨论】:

  • 试试这个:push @{ $_ }, \%new_hash for (values %mother_hash);
  • 谢谢,会的。
  • @HåkonHægland 如果您愿意,请将您的评论复制并粘贴到答案中。这是一个非常优雅的答案。
  • @ChristopherBottoms 谢谢,我将其添加为答案。

标签: arrays perl hash perl-data-structures


【解决方案1】:

如果你有一个散列数组的散列并且想要添加一个新的散列到 每个数组的末尾,你可以这样做:

push @{ $_ }, \%new_hash for (values %mother_hash);

此循环迭代 %mother_hash 的值(在本例中为数组引用)并为每次迭代设置 $_。然后在每次迭代中,我们将对新哈希 %new_hash 的引用推送到该数组的末尾。

【讨论】:

    【解决方案2】:

    首先我要指出子散列不是散列,而是匿名散列数组。添加另一个子哈希:

    $mother_hash{daughter_hash3} = [ { %daughter_hash3 } ];
    

    这将创建一个匿名数组,其中包含一个匿名哈希,其内容为%daughter_hash3。

    对于循环:

    $mother_hash{$daughter_hash_key} = [ { %daughter_hash } ];
    

    其中$daughter_hash_key 是一个字符串,其中包含%mother_hash 的键,%daughter_hash 是要添加的哈希值。

    使用键$daughter_hash_key 向子数组添加另一个哈希:

    push @{ $mother_hash{$daughter_hash_key} }, { %daughter_hash };
    

    我知道 ti 很复杂,但我建议您每次通过循环时使用 Data::Dumper 转储 %mother_hash 的内容,看看它是否正确增长。

    use Data::Dumper;
    print Dumper \%mother_hash;
    

    详情请见perldoc Data::Dumper..

    Data::Dumper 是 Perl 附带的标准模块。如需标准模块列表,请参阅perldoc perlmodlib。

    【讨论】:

    • 谢谢,谢谢@Shawn!
    【解决方案3】:

    mother_hash 是散列数组的散列。

    添加另一个顶级哈希数组。

    %mother_hash{$key} = [ { stuff }, { stuff } ];
    

    向现有数组添加另一个条目

    push @{%mother_hash{'key'}} { stuff };
    

    在嵌入数组的散列中添加另一个条目

    %{@{%mother_hash{'top_key'}}[3]}{'new_inner_key'} = value;
    

    当混淆并试图匹配包含哈希引用/数组引用的哈希/数组/标量的“类型”时,您可以使用以下技术

     use Data::Dumper;
     $Data::Dumper::Terse = 1;
     printf("mother_hash reference = %s\n", Dumper(\%mother_hash));
     printf("mother_hash of key 'top_key' = %s\n", Dumper(%mother_hash{top_key}));
    

    等等,以在大型数据结构中找到自己的方式,并验证您正在缩小到您想要访问或更改的区域。

    【讨论】:

    • 非常感谢@Edwin!
    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 2020-07-24
    • 2015-11-26
    • 2011-05-27
    相关资源
    最近更新 更多