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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.