Reputation: 2157
I have the following hash (result of print Dumper(\%hash)
)
$VAR1 = {
'A' => [
[
'1',
'PRESENT_1',
'ABSENT_2',
],
[
'2',
'PRESENT_1',
'ABSENT_2',
]
],
'B' => [
[
'5',
'PRESENT_1',
'ABSENT_2',
],
[
'6',
'PRESENT_1',
'ABSENT_2',
],
[
'7',
'ABSENT_1',
'PRESENT_2',
]
]
};
I'm looping through the hash & want to check if I can grep
a certain value in each of 'big' arrays.
But, I'm definitely doing something wrong here. The IF condition should be TRUE for array 'B', but not for 'A'. In 'A' you only have 'PRESENT_1' & 'ABSENT_2', so this should result in FALSE. In array 'B' you have both 'PRESENT_1' and 'PRESENT_2', so that should result in TRUE.
for my $key (keys %hash) {
if (( grep /"PRESENT_1"/, @{$hash{$key}} ) & ( grep /"PRESENT_2"/, @{$hash{$key}} )) {
print "# OK: " , $key, " ", @{$hash{$key}}, "\n";
} else {
print "# DISCARD: " , $key, " ", @{$hash{$key}}, "\n";
}
}
I guess my question is similar to this one: Perl Grep issue in nested hash/array, but I can't make it work.
Can somebody see what is wrong?
Upvotes: 1
Views: 184
Reputation: 62083
You need to dereference one more level. The linked Question is a HoA structure, but you have a HoAoA.
use warnings;
use strict;
my $VAR1 = {
'A' => [
[
'1',
'PRESENT_1',
'ABSENT_2',
],
[
'2',
'PRESENT_1',
'ABSENT_2',
]
],
'B' => [
[
'5',
'PRESENT_1',
'ABSENT_2',
],
[
'6',
'PRESENT_1',
'ABSENT_2',
],
[
'7',
'ABSENT_1',
'PRESENT_2',
]
]
};
my %hash = %{ $VAR1 };
for my $key (keys %hash) {
my $p1 = 0;
my $p2 = 0;
for my $aref (@{ $hash{$key} }) {
$p1 = 1 if grep /PRESENT_1/, @{ $aref };
$p2 = 1 if grep /PRESENT_2/, @{ $aref };
}
if ($p1 and $p2) {
print "# OK: $key\n";
}
else {
print "# DISCARD: $key\n";
}
}
Output:
# DISCARD: A
# OK: B
Upvotes: 2