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?
First of all, your 2 arrays need to be written correctly.
@a = ("abc","def","efg","ghy","klm","ghn");
@b = ("def","efg","ghy","klm","ghn","klm");
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 emulate pairwise
(if you don't have List::MoreUtils access) via:
if (@a != @b) {
$equals = 0;
} else {
$equals = 1;
foreach (my $i = 0; $i < @a; $i++) {
# Ideally, check for undef/value comparison here as well
if ($a[$i] != $b[$i]) { # use "ne" if elements are strings, not numbers
# Or you can use generic sub comparing 2 values
$equals = 0;
last;
}
}
}
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With