my $str = 'aabcdabcabcecdecd'; #### (abc => 3, bc => 3, cd => 3, ecd => 2) #### sub count1 { local $_=shift; my %count; for my $pos (0..(length)-1) { pos=$pos; @count{ /(.{2,}).*\1/g } = (); } for my $k (keys %count) { $count{$k} =()= /$k/g; } \%count; } #### $VAR1 = { 'cd' => 3, 'ecd' => 2, 'abc' => 3, 'bc' => 3 }; #### $VAR1 = { 'cd' => 3, 'c' => 5, 'ecd' => 2, 'a' => 4, 'abc' => 3, 'd' => 3, 'bc' => 3 }; #### sub count2 { my $s=shift; my %saw; my %count = map { map { $saw{$_}++ ? () : $_ => scalar(()= $s =~ /$_/g); } do { pos=$_; $s =~ /(.{2,}).*\1/g }; } 0..length($s)-1; \%count; } #### $VAR1 = { 'ecd' => 2, 'abc' => 3, '3' => 2 };