#!/usr/bin/perl -- use strict; use warnings; use Data::Dump; my @source=(1, 2, 3, 4, 5, 7); my @target=(0, 1, 3, 4, 6); my (@union, @intersection, @difference); my %count = (); foreach my $element (@source, @target) { $count{$element}++ } foreach my $element (keys %count) { push @union, $element; push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element; } dd \@source, \@target; dd \@union; dd \@intersection; dd \@difference; my @values_in_target_not_in_source = do { my %fuf; @fuf{ @union } = undef; delete @fuf{ @target }; keys %fuf; }; my @values_in_source_not_in_target = do { my %fuf; @fuf{ @union } = undef; delete @fuf{ @source }; keys %fuf; }; dd \@values_in_target_not_in_source , \@values_in_source_not_in_target ; __END__ ([1 .. 5, 7], [0, 1, 3, 4, 6]) [6, 4, 1, 0, 3, 7, 2, 5] [4, 1, 3] [6, 0, 7, 2, 5] ([7, 2, 5], [6, 0])