use strict; use warnings; my $string = 'ccaaactcagtggggtgaatggggcttctctgtgctctgatagcttccctaccctttcccttctccagctcccgtcccttctgactgtgagcagccccctcctctccactgttcccctcctgttgtcagaggagggcccagctgaggcagggactggaccaccggctggggtgtccctaggggtcttgggtggctggcagtagtggagcctggggctgagaggggaagcaaaataagattgtcctccaacttagccatcctcaggcctgctggggctatttaactggctgggcctgcatggcgacagggcccctacagcctccctgggaacaaggggtgaagggttcagggggaagggggtcacagagtgatggagaaacctcttgagaacaaactaggctccctcatgctggagtccaaggctgagtacctcccttctctgaaacagagcaacaaccccactcccaccccgagtctgtc'; my @keywords = qw( ttc gctg ccaac ggggct ccc ); my $substrlen = 3; # or use length of shortest element in @keywords # create an index of all substrings of length $string my %substrings; for( my $i = 0; $i <= length($string) - $substrlen; $i++ ) { my $substring = substr( $string, $i, $substrlen ); push( @{ $substrings{$substring}{hits} }, $i ); } # search the index for all elements of @keywords my %matches; foreach my $keyword ( @keywords ) { my $subkey = substr( $keyword, 0, $substrlen ); if( exists $substrings{$subkey} ) { foreach my $hit ( @{ $substrings{$subkey}{hits} } ) { if( $keyword eq substr($string, $hit, length($keyword)) ) { push( @{ $matches{$keyword} }, $hit ); } } } } foreach my $keyword ( keys %matches ) { print "Found $keyword ", scalar @{ $matches{$keyword} }; printf " time%s at position%s: ", scalar @{ $matches{$keyword} } > 1 ? 's' : '', scalar @{ $matches{$keyword} } > 1 ? 's' : ''; print join( ', ', @{ $matches{$keyword} } ), "\n"; } ** OUTPUT ** Found gctg 8 times at positions: 140, 164, 192, 214, 268, 286, 408, 421 Found ttc 8 times at positions: 25, 44, 55, 60, 78, 111, 344, 435 Found ccaac 1 time at position: 245 Found ccc 22 times at positions: 46, 51, 57, 70, 75, 94, 95, 96, 113, 114, 136, 174, 309, 310, 321, 401, 432, 456, 457, 463, 467, 468 Found ggggct 3 times at positions: 20, 211, 271