Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find elements that are in one array but not another in Perl?

Tags:

arrays

perl

I have two arrays and I want to find elements that are in one array but not another:

ex:

@array1 = ("abc", "cde", "fgh", "ijk", "lmn")
@array2 = ("abc", "fgh", "lmn")

I need to end up with:

@array3 = ("cde", "ijk")
like image 247
john Avatar asked Jul 16 '11 01:07

john


1 Answers

Put the elements of the second array into a hash, for efficient checking to see whether or not a particular element was in it, then filter the first array for just those elements that were not in the second array:

my %array2_elements;
@array2_elements{ @array2 } = ();
my @array3 = grep ! exists $array2_elements{$_}, @array1;
like image 145
ysth Avatar answered Sep 30 '22 22:09

ysth