@ids = ("a", "b", "c", "d", "e", "f", "g",); my %counts; foreach my $id (@ids) { open(FILE, "list.txt" ) || die "couldn't open 2\n"; $/ = undef; while () { if (/$id/g) { $counts{$id}++; } else { print "$id not found\n"; } } close FILE; } use Data::Dumper; print Dumper \%counts; #### a b b c c d d d f f f #### e not found g not found $VAR1 = { 'f' => 1, 'c' => 1, 'b' => 1, 'd' => 1, 'a' => 1 }; #### e not found g not found $VAR1 = { 'f' => 3, 'c' => 2, 'b' => 2, 'd' => 3, 'a' => 1 };