简体   繁体   中英

Filter array of hash references in perl

Is it possible to filter the output generated by an Array of hashreferences to only print that array elements hash reference if it contains a specific key or value, with that i mean print out the entire hash of that array element. This example code would print out every hash in every element:

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

How would i go about filtering that output to only print the elements that has a hashref that contain a certain key or value ?

Example hashref in :

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

output:
husband=fred wife=wilma daughter=pebbles

Example data would only be printed out if it one of the keys (husband/wife/daughter) or one of the values (fred/wilma/pebbles) were specified in some sort of if-statement(?)

Just add

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

after the first for . It will skip the hash if the husband key doesn't exist in it.

To filter the values, use either

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

or

next unless { reverse %{ $AoH[$i] } }->{homer};
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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM