I have two arrays, @a
and @b
. I want to do a compare among the elements of the two arrays.
my @a = qw\"abc def efg ghy klm ghn\";
m
This question still could mean two things where it states "If any element matches then set a flag":
For case 1, you might do this:
# iterate over all positions, and compare values at that position
my @matches = grep { $a[$_] eq $b[$_] } 0 .. $#a;
# set flag if there's any match at the same position
my $flag = 1 if @matches;
For case 2, you might do that:
# make a hash of @a and check if any @b are in there
my %a = map { $_ => 1 } @a;
my @matches = grep { $a{$_} } @b;
# set flag if there's matches at any position
my $flag = 1 if @matches;
Note that in the first case, @matches holds the indexes of where there are matching elements, and in the second case @matches holds the matching values in the order in which they appear in @b.