The snippet finds all the common elements across a list of arrays.

It is similar to List::Compare's get_intersection except that it returns all the common elements, rather than a list of the unique common elements:

findCommon ([1, 2, 2], [2, 2, 3]);

would return (2, 2) for example.

Gotchas

Note that Storable's dclone can be used to efficiently copy the lists if required.

sub findCommon { my @lists = @_; my @common; while (@lists == grep {@$_} @lists) { my %hits; $hits{$_->[0]}++ for @lists; my $least = (sort keys %hits)[0]; push @common, $least if $hits{$least} == @lists; $_->[0] eq $least && shift @$_ for @lists; } return @common; }