RSS
 

Finding an Intersection Between Arrays in Perl

15 Jul

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.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)
Retweet
 
3 Comments

Posted in Perl

 
  1. me

    May 1, 2008 at 7:56 pm

    dud line:

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

    should be:

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

    VA:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.3_1094]
    Rating: 0 (from 0 votes)
     
  2. chovy

    May 28, 2008 at 11:09 pm

    thanks for catching that.

    VN:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.3_1094]
    Rating: 0 (from 0 votes)
     
  3. Daniel

    November 13, 2008 at 10:20 am

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

    VA:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.3_1094]
    Rating: 0 (from 0 votes)