use strict; use warnings; use Data::Dumper; my $file = \"a\nb\nb\nc\nc\nd\nd\nd\nf\nf\nf"; # In memory 'file' my @ids = qw( a b c d e f g ); open my $FILE, '<', $file or die "cannot open input file"; my @lines = <$FILE>; # Read entire file into an array close $FILE; my %counts; ID: foreach my $id (@ids) { my $count = grep { /$id/ } @lines; if ($count) { $counts{$id} = $count; next ID; } warn "$id not found\n"; } print Dumper \%counts;