user145265
user145265

Reputation: 35

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(?)

Upvotes: 2

Views: 1782

Answers (2)

choroba
choroba

Reputation: 241848

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};

Upvotes: 0

ikegami
ikegami

Reputation: 385657

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);
}

Upvotes: 0

Related Questions