Check if the array contains a value from another array

I have an array of objects and an array of valid return values ​​for a specific method. How to reduce an array of objects only to those whose method in question returns a value in my array of valid values?

Now I have this:

my @allowed = grep {
    my $object = $_;
    my $returned = $object->method;
    grep {
        my $value = $_;
        $value eq $returned;
    } @acceptableValues;
} @objects;

The problem is that this is a complex cycle that I would like to avoid. This program is designed to scale to arbitrary sizes, and I want to minimize the number of iterations performed.

What is the best way to do this?

+6
source share
2 answers

You can convert accepted return values ​​to hash

my %values = map { $_ => 1 } @acceptedValues;

grep , grep:

my @allowed = grep $values{ $_->method }, @objects;

, grep , , . , , . , , , . , , - .

+7

, , . , , . 1, .

my %values;
my @allowed;
map {$values{$_}++} (@acceptableValues, @objects);
for (keys %values) {
    push @allowed, $_ if $values{$_} > 1;
}
0

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


All Articles