my $ref = 'agctagctagctagcatgctagctagctgatcgatgctagctagctgactgacgacg'; my @subseq_to_find = qw{ gctagctag tagcatgctagctag gctagctgac tag }; my @output; for my $subseq ( @subseq_to_find ) { my $p = -1; MATCH: while (1) { $p = index $ref, $subseq, $p + 1; last if $p < 0; my $len = length $subseq; for ( @output ) { my $substr = \ substr $_, $p, $len; $$substr = $subseq and next MATCH unless $$substr =~ /\S/; } push @output, " " x length $ref; substr $output[-1], $p, $len, $subseq; } } print "$_\n" for $ref, @output;