in reply to How do I compare two arrays?

You've already got a pointer to the QA section.

Another solution (that I didn't see mentioned there) is to transfer elements of one array into a hash, and use that.

Such a method uses more memory space but is faster (unless you use so much memory you start swapping :-)

The code would look somewhat like this:

map($a1{$_}=1,@a1); # create %a with elements from @a1 @a2=grep(!defined($a1{$_}),@a2); # returns those elements of @a2 that +don't # have a hash element in %a1 therefore they # do not exist in @a1.

Replies are listed 'Best First'.
Re: Re: How do I compare two arrays?
by Corion (Patriarch) on Mar 09, 2004 at 08:07 UTC

    You should be more careful with your assertions:

    @a1 = qw(1 2 2 3); @a2 = qw(1 2 3 3);

    Your code will consider @a1 and @a2 as equal when they clearly aren't. Your solution can only work when all array elements are unique and the order of elements is irrelevant. The original poster possibly wants an unordered comparision, but the problem with multiple identical elements remains.

    If you modify your code to use the hash as a counter, then it works better:

    use strict; sub dec($) { $_[0] ? $_[0]-- : 0 }; my @a1 = qw(1 2 2 3); my @a2 = qw(1 2 3 3); my %a1; $a1{$_}++ for (@a1); my @only_a2 = map { dec $a1{$_} ? () : $_ } @a2; print "Only in \@a2 : @only_a2\n";

    In the end, I guess what the poster really wants is what's called the symmetric difference between two sets, which is what you (for example) get by building @only_a1 and @only_a2.