Is there any easy way to compare two string arrays in Perl?
@array1 = (value1, value2, value3...);
@array2 = (value1, value3, value4...);
I need the comparison like below for "N" Number of values,
value1 eq value1
value2 eq value3
value3 eq value4
Please suggest me is there any module to do this?
Thanks
Hmm... a module to compare arrays, you say. How about Array::Compare?
use Array::Compare;
my $compare = Array::Compare->new;
my @array1 = (value1, value2, value3...);
my @array2 = (value1, value3, value4...);
if ($compare->compare(\@array1, \@array2) {
say "Arrays are the same";
} else {
say "Arrays are different";
}
But you can also use the smart match operator.
if (@array1 ~~ @array2) {
say "Arrays are the same";
} else {
say "Arrays are different";
}
You can compare sizes of both arrays (@a1 == @a2
in scalar context), and then compare size of @a1
array with size of list of indices which correspond to equal strings in both arrays (grep $a1[$_] eq $a2[$_], 0..$#a1
),
if (@a1 == @a2 and @a1 == grep $a1[$_] eq $a2[$_], 0..$#a1) { print "equal arrays\n" }
More performance oriented version (doesn't go through all elements if not necessary),
use List::Util 'all';
if (@a1 == @a2 and all{ $a1[$_] eq $a2[$_] } 0..$#a1) { print "equal arrays\n" }
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