Monday, May 5, 2008

perl: testing two arrays for equivalence

How do I test whether two arrays or hashes are equal?

The following code works for single-level arrays. It uses a string-wise comparison, and does not distinguish defined versus undefined empty strings. Modify if you have other needs.

unless ( arrays_are_equal (\@tmp1, \@tmp2) ){
    print "\ntmp1 and tmp2 are not equal!\n";
}
else {
    print "\ntmp1 and tmp2 are indeed equal!\n";
}


sub arrays_are_equal {
    my ($first, $second) = @_;
    no warnings; # silence spurious -w undef complaints
    return 0 unless @$first == @$second;
    
    for (my $i = 0; $i < @$first; $i++) {
        return 0 if $first->[$i] ne $second->[$i];
    }
    return 1;
}

Source: perldoc -q "How do I test whether two arrays"

No comments: