my @A = (1,2,3,4,5,4,3,2,1,2); my @B = (2,4,6,8,10,8,6,4,2); my (%First, %Second); push @{ $First{ $A[$_] } }, $_ for (0..$#A); push @{ $Second{ $B[$_] } }, $_ for (0..$#B); my %Pairs; for my $Common (grep {exists $Second{$_}} keys %First){ for my $Idx (@{ $First{$Common} }){ push @{ $Pairs{$Common} }, map([$Idx, $_], @{ $Second{$Common} }); } } # Print out what we found for (sort keys %Pairs){ print "$_:\n", map(" $_\n", map(join('-', @$_), @{ $Pairs{$_} })), "\n"; }