use strict; use warnings; my %content; for my $animal ('dog', 'cat') { open my $fh, '<', "/tmp/$animal.txt" or die "Couldn't open $animal: $!"; while ( my $line = <$fh> ) { ++$content{$animal}{$line}; } } for my $animal ('horse', 'lama', 'camel', 'tiger') { open my $fh, '<', "/tmp/$animal.txt" or die "Couldn't open $animal: $!"; while ( my $line = <$fh> ) { for my $other ('cat', 'dog') { print "$other: $line" if $content{$other}{$line}; } } }