过滤perl中的哈希引用数组

时间:2016-02-17 15:21:27

标签: arrays perl hash

是否可以过滤由hash引用数组生成的输出,只打印该数组元素哈希引用(如果它包含特定的键或值),我的意思是打印出该数组元素的整个哈希值。此示例代码将打印出每个元素中的每个哈希:

for $i ( 0 .. $#AoH ) {
 print "$i is { ";
 for $role ( keys %{ $AoH[$i] } ) {
     print "$role=$AoH[$i]{$role} ";
 }
 print "}\n";
}

如何过滤该输出以仅打印具有包含特定键或值的hashref的元素?

示例hashref in:

push @AoH, { husband => "fred", wife => "wilma", daughter => "pebbles" };

output:
husband=fred wife=wilma daughter=pebbles

只有在其中一个键(丈夫/妻子/女儿)或其中一个值(fred / wilma / pebbles)在某种if语句(?)

2 个答案:

答案 0 :(得分:0)

添加

next unless exists $AoH[$i]{husband};

在第一个for之后。如果husband密钥不存在,它将跳过散列。

要过滤值,请使用

next unless grep 'john' eq $_, values %{ $AoH[$i] };

next unless { reverse %{ $AoH[$i] } }->{homer};

答案 1 :(得分:0)

my %keys_to_find = map { $_ => 1 } qw( husband wife daughter );
my %vals_to_find = map { $_ => 1 } qw( fred wilma pebbles );

for my $person (@persons) {
   my $match =
      grep { $keys_to_find{$_} || $vals_to_find{$person->{$_}} }
         keys(%$person);

   next if !$match;

   say
      join ' ',
         map { "$_=$person->{$_}" }
            sort keys(%$person);
}
相关问题