Perl newbie here… need some help and suggestions. I’ve searched for many examples but so far it’s all for array operation for two arrays. I have three arrays and want to find the common value in the three array and list them out :

Array 1 = {0, 1,2,3,4,5,6,7,8,9}
Array 2 = {1,2,3,4,6,8, 10, 12,14}
Array 3 = {1,2,3,5,7,9, 11,13,15}

I want the output to be something like below:

Array 1 	Array 2	   Array 3
0	yes		
1	yes		yes		yes
2	yes		yes		yes
3	yes		yes		yes
4	yes		yes		
5	yes				yes
6	yes		yes		
7	yes				yes
8	yes		yes		
9	yes				yes
10			yes		
11					yes
12			yes		
13					yes
14			yes		
15					yes

The idea is to list out the output as above. I’ve started with something below which I got from another website but got stuck :

#!/usr/bin/perl
use strict;
use warnings;
my @array1;
my @array2;
my @diff;
my @isect;
my $item;
my %count;
@array1 = (0, 1,2,3,4,5,6,7,8,9);
@array2 = (1,2,3,4,6,8, 10, 12,14);
@isect = ( );
@diff = ( );
%count = ( );
foreach $item (@array1, @array2) { $count{$item}++;}
foreach $item (keys %count) {
if ($count{$item} == 2) {
push @isect, $item;
} else {
push @diff, $item;
}
}
print "\nA Array = @array1\n";
print "\nB Array = @array2\n";
print "\nIntersect Array = @isect\n";
print "\nDiff Array = @diff\n\n";

Appreciate the help

#!/usr/bin/perl
#ElementsIn3Arrays.pl
use 5.006;
use strict;
use warnings;

my @a1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
my @a2 = (1, 2, 3, 4, 6, 8, 10, 12, 14);
my @a3 = (1, 2, 3, 5, 7, 9, 11, 13, 15);
my %h = ();
my $item;

foreach $item (@a1, @a2, @a3) {$h{$item}++}; #Build hash of unique values
printf("%4s%20s%20s%20s\n", "Elem", "Array1", "Array2", "Array3");
foreach $item (sort {$a<=>$b} (keys (%h))) {
	printf "%4s%20s%20s%20s\n", $item, is_in($item, \@a1), is_in($item, \@a2), is_in($item, \@a3);
}

sub is_in {
	my ($element, $array_ref) = @_;
	my @array = @{$array_ref};
	if (grep {$_ eq $element} @array) {
		return 'Yes'; #Found it
	}
return ''; #Didn't find it
}
#!/usr/bin/perl
#ElementsIn3Arrays.pl
use 5.006;
use strict;
use warnings;

my @a1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
my @a2 = (1, 2, 3, 4, 6, 8, 10, 12, 14);
my @a3 = (1, 2, 3, 5, 7, 9, 11, 13, 15);
my %h = (); #Empty hash
my $item;
# Fill hash with unique keys from all 3 arrays
# and add references to hashes with keys Array 1 .. 3 
# and value 1 (indicating 'true') when item is in that array
foreach $item (@a1) {$h{$item}->{'Array 1'} = 1};
foreach $item (@a2) {$h{$item}->{'Array 2'} = 1};
foreach $item (@a3) {$h{$item}->{'Array 3'} = 1};
printf("%4s%15s%15s%15s\n", "Elem", "Array 1", "Array 2", "Array 3");

foreach $item (sort {$a<=>$b} (keys (%h))) {
	printf "%4s%15s%15s%15s\n", $item, 
	 ($h{$item}->{'Array 1'}) ? "Yes" : "",
	 ($h{$item}->{'Array 2'}) ? "Yes" : "",
	 ($h{$item}->{'Array 3'}) ? "Yes" : "";
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.