Benchmark: timing 2000 iterations of Krambambuli, blazar... Krambambuli: 4 wallclock secs ( 3.28 usr + 0.01 sys = 3.29 CPU) @ 607.90/s (n=2000) blazar: 1 wallclock secs ( 0.80 usr + 0.00 sys = 0.80 CPU) @ 2500.00/s (n=2000) #### use strict; use warnings; use Benchmark; use Data::Dumper; use constant MIN => 2; my $str = 'aabcdabcabcecdecd'; my $min_length = 2; my $min_count = 2; timethese(2000, { 'blazar' => sub { count1( $str ) }, 'Krambambuli' => sub { count2( $str ) }, }); { my %count; sub count1 { my( $string) = @_; my $length = length( $string ); if ($length < MIN) { $count{$_} == 1 and delete $count{$_} for keys %count; return \%count; } for my $l (MIN..$length) { my $s = substr( $string, 0, $l ); $count{ $s } += 1; } count1( substr( $string, 1 ) ); } } sub count2 { local $_=shift; my $l=length; my %count; for my $off (0..$l-1) { for my $len (MIN .. $l-$off) { my $s=substr $_, $off, $len; $count{ $s } ||= ()= /$s/g; } } $count{$_} == 1 and delete $count{$_} for keys %count; \%count; }