in reply to Compare arrays

What have you tried? What didn't work? See How do I post a question effectively?. We really like to see your code so we can help you become a better programmer.

This is closely related to some FAQs: How can I tell whether a certain element is contained in a list or array? and How do I compute the difference of two arrays? How do I compute the intersection of two arrays?. The short answer is use a hash:

#!/usr/bin/perl use strict; use warnings; my @array1 = qw(a b c e); my @array2 = qw(a b c d); my %hash; for my $key (@array2) { $hash{$key}++; } for my $key (@array1) { print "Fail: $key\n" unless $hash{$key}; }

Replies are listed 'Best First'.
Re^2: Compare arrays
by Anonymous Monk on Nov 01, 2010 at 18:11 UTC
    Out of interest using your code as a base how do I print both of the array elements that have caused the mismatch ? e.g.
    array1 = "e" array2 = "d"
      There are a couple ways to interpret this question. I will assume you mean you would like the elements of each array that are excluded from the union of the two.

      #!/usr/bin/perl use strict; use warnings; my @array1 = qw(a b c e); my @array2 = qw(a b c d); my %hash; for my $key (@array2) { $hash{$key}++; } for my $key (@array1) { print "Fail #1: $key\n" unless $hash{$key}--; } for my $key (keys %hash) { print "Fail #2: $key\n" if $hash{$key} > 0; }

      For other related solutions, check out How do I compute the difference of two arrays? How do I compute the intersection of two arrays? in perlfaq4