List::Compare is the tool generally used for this sort of thing:
use strict;
use warnings;
use List::Compare;
my @AllArraysIHave = ([1,2,3,4,5], [2,3,6,7,8,8,8,9,10], [5,6,2,3]);
my $lc = List::Compare->new('-u', @AllArraysIHave);
my @result = $lc->get_intersection;
print "@result";
Prints:
3 2
Update: speed is disapointing though (listCompareF use the functional interface):
manual: 3 2
listCompareF: 2 3
listCompare: 3 2
Rate listCompare listCompareF manual
listCompare 1128/s -- -70% -93%
listCompareF 3822/s 239% -- -78%
manual 17051/s 1411% 346% --
use strict;
use warnings;
use List::Compare;
use List::Compare::Functional qw(get_intersection);
use Benchmark qw(cmpthese);
my @AllArraysIHave = ([1,2,3,4,5], [2,3,6,7,8,8,8,9,10], [5,6,2,3]);
my @result = @{manual ()};
print "manual: @result\n";
@result = @{listCompareF ()};
print "listCompareF: @result\n";
@result = @{listCompare ()};
print "listCompare: @result\n";
cmpthese (-1,
{
manual => \&manual,
listCompare => \&listCompare,
listCompareF => \&listCompareF,
}
);
sub manual {
my %intersection;
my @result;
foreach my $dataArray(@AllArraysIHave) {
my %lookuptable;
foreach(@{$dataArray}) {
if (!$lookuptable{$_}) {
$lookuptable{$_} = 1;
$intersection{$_}++;
}
}
}
my $amnt = scalar(@AllArraysIHave);
foreach my $key (keys %intersection) {
if ($intersection{$key} == $amnt) {
push @result, $key;
}
}
return \@result;
}
sub listCompare {
my $lc = List::Compare->new('-u', @AllArraysIHave);
my @result = $lc->get_intersection;
return \@result;
}
sub listCompareF {
my @result = get_intersection ([@AllArraysIHave]);
return \@result;
}
DWIM is Perl's answer to Gödel
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|