use strict; sub get_animal { open my $FILE, '<', shift or die $!; return map {chop; $_ => $_} <$FILE>; } my %a = get_animal '/tmp/first.txt'; my %b = get_animal '/tmp/second.txt'; { print "$_\n" for grep {$_} @a{keys %b}; }