Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare arrays in Perl?

Tags:

arrays

perl

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?

like image 700
devtech Avatar asked Apr 07 '10 10:04

devtech


1 Answers

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.

like image 180
DVK Avatar answered Nov 05 '22 13:11

DVK