Finding an Intersection Between 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.

VN:F [1.8.4_1055]
Rating: 0.0/10 (0 votes cast)
VN:F [1.8.4_1055]
Rating: 0 (from 0 votes)

3 Responses to “Finding an Intersection Between Arrays in Perl”

  1. me says:

    dud line:

    map { $original{$_} => 1 } @array1;

    should be:

    map { $original{$_} = 1 } @array1;

    UN:F [1.8.4_1055]
    Rating: 0.0/5 (0 votes cast)
    UN:F [1.8.4_1055]
    Rating: 0 (from 0 votes)
  2. chovy says:

    thanks for catching that.

    UA:F [1.8.4_1055]
    Rating: 0.0/5 (0 votes cast)
    UA:F [1.8.4_1055]
    Rating: 0 (from 0 votes)
  3. Daniel says:

    How about the complement of two arrays?
    How can i do that?

    UN:F [1.8.4_1055]
    Rating: 0.0/5 (0 votes cast)
    UN:F [1.8.4_1055]
    Rating: 0 (from 0 votes)

Leave a Reply