foreach $x (@A){ foreach $y (@B){ if ($y eq $x){ print "$y\n"; } elsif ($x ne$y){ print "$x"; } } }