Compare two arrays with Perl

Is there an easy way to compare two string arrays in Perl?

@array1 = (value1, value2, value3...); @array2 = (value1, value3, value4...); 

I need to compare, as shown below for the "N" number of values,

 value1 eq value1 value2 eq value3 value3 eq value4 

Please suggest me is there any module for this?

thanks

+6
source share
4 answers

Hmm ... module for comparing arrays, you say. What 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"; } 
+7
source

Perl already has some parts for dealing with any list operations.

See List::Util and List::MoreUtils .

 my $arrays_are_equal = !List::Util::pairfirst { $a ne $b } # first case where $a != $b List::MoreUtils::zip( @array1, @array2 ) ; 

For this application, see List::Util::pairfirst and List::MoreUtils::zip

+3
source

You can compare the sizes of both arrays ( @a1 == @a2 in a scalar context), and then compare the size of the @a1 array with the size of the list of indexes that correspond to the same rows in both arrays ( grep $a1[$_] eq $a2[$_], 0..$#a1 ),

 if (@a1 == @a2 and @a1 == grep $a1[$_] eq $a2[$_], 0..$#a1) { print "equal arrays\n" } 

A more performance-oriented version (does not go through all the elements if necessary),

 use List::Util 'all'; if (@a1 == @a2 and all{ $a1[$_] eq $a2[$_] } 0..$#a1) { print "equal arrays\n" } 
+3
source

This task is simple enough that I will not necessarily use the CPAN module. Instead, I would most likely write my own comparison routine and put it in my own utility module. Here is one implementation that will compare two arrays containing strings and / or integers.

 #!/usr/bin/env perl use strict; use warnings; my @array1 = (1..10, 'string'); my @array2 = (1..10, 'string'); my $is_same = is_same(\@array1, \@array2); print "is_same: $is_same\n"; sub is_same { my($array1, $array2) = @_; # immediately return false if the two arrays are not the same length return 0 if scalar(@$array1) != scalar(@$array2); # turn off warning about comparing uninitialized (undef) string values # (limited in scope to just this sub) no warnings; for (my $i = 0; $i <= $#$array1; $i++) { if ($array1->[$i] ne $array2->[$i]) { return 0; } } return 1; } 
+1
source

Source: https://habr.com/ru/post/978349/


All Articles