Click to See Complete Forum and Search --> : Comparing two arrays


JDWilliams
07-19-2006, 11:22 AM
I've got two arrays. Array1 has around 200 phone numbers. Array2 has around 600 phone numbers. What I would like to do compare the two and generate a third array that has numbers from Array2 that don't have a match in Array1.

What's the most efficient way to do this? Grep? I'll have a cgi script doing this and will want to minimize the time that it takes for this to run. I typically seem to come up with the most cumbersome and processor intensive code for these sort of things.

Charles
07-19-2006, 12:34 PM
#!\perl\bin\perl.exe

@array_one = qw(one two three four);
@array_two = qw(three four five six);

%array_one = map {$_, 1} @array_one;
@difference = grep {!$array_one {$_}} @array_two;

print "@difference\n";

JDWilliams
07-19-2006, 05:34 PM
Thanks Charles. That's more elegant than what I had. Seems quicker too. I'm going to have to play around with map & grep a little more. That seems to be something I should be using more of.

chrisranjana
07-26-2006, 11:51 AM
The perl faq (http://perldoc.perl.org/perlfaq4.html) has many more techniques for manipulating hashes and arrays.