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";
my @b = qw"def ghy jgk lom com klm";
If any element matches then set a flag. Is there any simple way to do this?
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";
my @b = qw"def ghy jgk lom com klm";
If any element matches then set a flag. Is there any simple way to do this?
IMHO, you should use List::MoreUtils::pairwise. However, if for some reason you cannot, then the following sub would return a 1 for every index where the value in the first array compares equal to the value in the second array. You can generalize this method as much as you want and pass your own comparator if you want to, but at that point, just installing List::MoreUtils would be a more productive use of your time.
Note that you will need Perl 5.10, or later, to use the smart match operator (
~~
) .First of all, your 2 arrays need to be written correctly.
Second of all, for arbitrary arrays (e.g. arrays whose elements may be references to other data structures) you can use
Data::Compare
.For arrays whose elements are scalar, you can do comparison using
List::MoreUtils
pairwise BLOCK ARRAY1 ARRAY2
, where BLOCK is your comparison subroutine. You can emulatepairwise
(if you don't have List::MoreUtils access) via:P.S. I am not sure but List::Compare may always sort the lists. I'm not sure if it can do pairwise comparisons.
If you would consider the arrays with different order to be different, you may use Array::Diff
Brute force should do the trick for small a
n
:For a large
n
, use a hash table:Where a large
n
is|@a| + |@b| > ~1000
items