# initialize the array of patterns # the same code as you use in your script, just complete the line my @pat_array = ...; # this is new hash variable used for counting matches # it used entirely instead your approach my %match_count; # skip first lines # simple read them and do nothing over them for ( 1..$InStartLineNumber ); # normal work # read line by line the rest of the file and do something while ( ) { # read the line, and store in the variable explicitly chomp; my $line = $_; # walk through the list of patterns # test the line for matching each pattern # and count every successful match in the hash map { $line =~ m/\Q$_\E/ and $match_count{$_}++; } @pat_array; } # The rest of code handling with @pat_array and %match_count