# suppose this is the input string my $str_in; # and this is the output my $str_out; my $char; my $char_count; my $len = length $str_in; for (my $i=0; $i<$len; $i++) { my $curr = substr $str_in,$i,1; if (!defined $char) { # initialize state $char = $curr; $char_count = 1; } else { if ($curr eq $char) { # current char is same with previous ones if ($char_count>=3) { $char_count++; } else { $str_out .= $curr; $char_count++; } } else { # we found a different char $char = $curr; $char_count = 1; $str_out .= $curr; } } }