my %temp_for_compare;
# Add values from the first array into the temporary hash
$temp_for_compare{$_} = 0 for @array1;
# Now we can simply check the items in the second array against the hash
for my $val (@array2) {
if (exists $temp_for_compare{$val}) {
print "$val in both arrays\n";
}
}
####
for my $a1val (@array1) {
for my $a2val (@array2) {
if ($a1val eq $a2val) {
print "$a1val in both arrays\n";
}
}
}
####
my @tmpArray1 = sort @array1;
my @tmpArray2 = sort @array2;
# You run out of matches when either array is empty
while (@tmpArray1 and @tmpArray2) {
if ($tmpArray1[0] eq $tmpArray2[0]) {
print "$tmpArray1[0] in both arrays\n";
shift @tmpArray1;
shift @tmpArray2;
}
elsif ($tmpArray1[0] lt $tmpArray2[0]) {
# tmpArray1 has an item not in tmpArray2, so get rid of
# it and try the next element
shift @tmpArray1;
}
else {
# tmpArray2 has an item not in tmpArray1, so get rid of
# it and try next element
shift @tmpArray2;
}
}