0
votes

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

2
Please provide example data. Also, take a look at p3rl.org/Data::Printersimbabque
You could grep for it ?123
I'm not sure about the syntax for grepping a hashrefuser145265

2 Answers

0
votes

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