Tuesday, September 13, 2011

A little perl nugget: differences between two arrays

Something small, simple...

I have two perl arrays and I want to remove all elements in common between the two arrays, leaving only the elements in list_one that are unique to list_one.


For example pre-populate two arrays with the following values.
my @list_one = ();
push(@list_one,'a');
push(@list_one,'b');
push(@list_one,'c');

my @list_two = ();
push(@list_two,'b');


The commands below create a map of the list_one array, while the delete command removes matching elements found in list_two. Finally the map is converted back to an array.

my %diff2;
@diff2{ @list_one } = @list_one;
delete @diff2{ @list_two };
my @new_list_one = values %diff2;

And the expected result below.
$VAR1 = 'c';
$VAR2 = 'a';

No comments:

Post a Comment