Print an array hash key if any element of the array matches another array

I have an array like this:

my @arr = (5, 76, 1000, 21, 47);

And this hash:

my %hash = (
      Meta => [1000],
);

If any of the hash values ​​matches any of the elements in the array, I want to print the key value of this match. For this, I use the following function, and it works:

my ($match) = grep { "@{$hash{$_}}" ~~ @arr } keys %hash;

The problem arises when there is more than one element in the hash of arrays, for example:

my %hash = (
      Meta => [1000, 2],
);

In this case, I also want to return the key ("Meta"), since the value 1000 is in the array, but I do not understand it.

+4
source share
2 answers

You can use intersectfrom Array :: Utils to do this.

use strict;
use warnings;
use Array::Utils 'intersect';

my @arr = (5, 76, 1000, 21, 47);
my %hash = (
      Meta => [1000, 2],
      Foo  => [1, 2, 3],
      Bar  => [47],
);

my @match = grep { intersect(@{$hash{$_}}, @arr) } keys %hash;

p @match;

Fingerprints:

[
    [0] "Bar",
    [1] "Meta"
]

. $match @match, , .

+5

, Array:: Utils intersect, %set1 ( %groups):

my @set1 = (5, 76, 1000, 21, 47);
my %set1 = map { $_ => 1 } @set1;

my %groups = (
   Meta => [1000, 2],
   Foo  => [1, 2, 3],
   Bar  => [47],
);

my @matches = grep { 
    my $set2 = $groups{$_};
    grep { $set1{$_} } @$set2
} keys %groups;

grep, grep .

+5

Source: https://habr.com/ru/post/1623785/