Chovy’s Blog

Finding an Intersection Between Arrays in Perl

Thu, May 17, 2007 — Category: 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.

  • Post Finding an Intersection Between Arrays in Perl to del.icio.us
  • Post Finding an Intersection Between Arrays in Perl to digg
  • Post Finding an Intersection Between Arrays in Perl to Furl
  • Add Finding an Intersection Between Arrays in Perl to YahooMyWeb
  • Simpify!
  • Post Finding an Intersection Between Arrays in Perl to shadows
  • Post Finding an Intersection Between Arrays in Perl to Spurl
  • Post Finding an Intersection Between Arrays in Perl to BuddyMarks
  • Submit Finding an Intersection Between Arrays in Perl to Slashdot

2 Comments »

Comment by me

May 1, 2008 @ 7:56 pm

dud line:

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

should be:

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

Comment by chovy

May 28, 2008 @ 11:09 pm

thanks for catching that.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

 
Keyword Advertisers:
SEO Directory SEO Links Free Link Directory Shopping Submission Directory Gardening Tips Political Forum Search Engine Optimization Search Engine Marketing Audio Video Directory SEO Forum Web Development Blog Organic SEO Wiki Web Development Consulting

Learn more about purchasing keyword text link ads on this site.