A small thing, but you do not seem to use the loop variable ($_) value in your foreach loops. Therefore it might be better to write the sequence starting from 1 and remove the subtraction, for example: foreach (0.. (length($sequence)-1)) becomes: foreach (1.. (length $sequence))