Finding an Intersection Between Arrays in Perl
Short recipe for grabbing an intersection between two arrays in Perl.
As explained on perl monks and Pete Kruckenberg’s post…I needed a similar function that returns an intersection between two arrays in Perl.
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
my @array1 = (1, 2, 3);
my @array2 = (2, 3, 4);
my %original = ();
my @isect = ();
map { $original{$_} => 1 } @array1;
@isect = grep { $original{$_} } @array2;
print Dumper(@isect);
#outputs
#$VAR1 = 2;
#$VAR2 = 3;
The above code works with duplicates, meaning that duplicates in @array2 will be added as individual elements in the array @isect.



















