my $str = "BEBEBEHUHUHUJJFAFALL"; my $length = 2; my $index = 0; my %cnt; # hash to store the counters while (1) { # infinite loop my $substring = substr $str, $index, $length; # getting a substring of $length length, starting at offet $index (initially 0) last if length($substring) < $length; # exiting the infinite loop if we are at the end of the string $cnt{$substring}++; # increasing the counter for the substring $index += $length; # increasing the offset by $length }