代码之家  ›  专栏  ›  技术社区  ›  Mike

Perl,获取所有哈希值

  •  7
  • Mike  · 技术社区  · 14 年前

    比如说,在Perl中,我有一个哈希引用列表,每个哈希引用都需要包含一个特定的字段。 foo . 我想创建一个包含所有映射的列表 . 如果有一个哈希不包含 这个过程应该失败。

    @hash_list = (
     {foo=>1},
     {foo=>2}
    );
    
    my @list = ();
    foreach my $item (@hash_list) {
       push(@list,$item->{foo});
    }
    
    #list should be (1,2);
    

    在Perl中有没有更简洁的方法可以做到这一点?

    4 回复  |  直到 14 年前
        1
  •  6
  •   Evan Carroll    14 年前

    对。有。

    my @list = map {
        exists $_->{foo} ? $_->{foo} : die 'hashed lacked foo'
      }
      @hash_list
    ;
    
        2
  •  2
  •   Peter Tillemans    14 年前

    您可以为此使用map函数:

    @hash_list = (
     {foo=>1},
     {foo=>2}
    );
    
    @list = map($_->{foo}, @hash_list);
    

    map将第一个参数中的函数应用于第二个参数的所有元素。

    grep也很酷,可以过滤列表中的元素,并且工作方式相同。

        3
  •  1
  •   Daenyth    14 年前

    Evan的答案很接近,但将返回hashrefs而不是foo的值。

    my @list = map $_->{foo} grep { exists $_->{foo} } @hash_list
    
        4
  •  0
  •   Eugene Yarmash    14 年前
    if ( @hash_list != grep { exists $_->{foo} } @hash_list ) {
        # test failed
    }