Friday, September 22, 2006

Linux:: How to compare two list and find common element with Perl?

This trick can only be used if you are sure that there is no double value in a same list. You will understand why. First create an hash table (%seen), the basic idea is for each element ($_) of the merge of the two list, we will store it in the hash table. The first time the value is store; seen value is equal to 0, so the grep filter prevents this value to be record in @common. The second and other time an element will be seen, because it will be store with the same key value, the $seen{$_ } will be not null and so the element pass the test of the filter and is recorded.

my %seen;
my @common = grep {$seen{$_}++} @list_1 , @list_2;

but for doing that you need that list are unique (not two times the same element in the same list.) For doing that you can use this function:

sub Array_Uniq
my @List = @_;
my %FutureList;
$FutureList{$_} = 1; # delete double values
return (keys(%FutureList));

No comments: