Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two arrays in a easy way using Perl

Tags:

cgi

perl

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

like image 525
Vasanth Avatar asked Nov 18 '14 18:11

Vasanth


2 Answers

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";
}
like image 160
Dave Cross Avatar answered Sep 21 '22 16:09

Dave Cross


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" }
like image 33
mpapec Avatar answered Sep 22 '22 16:09

mpapec