use strict; use warnings; my @strs = ( '010111', '0' x 1_000_000, '01' x 1_000_000, '011' x 1_000_000, ( '01' x 1_000_000 ) . '111', ); for my $str (@strs) { my $len = ( () = $str =~ m{ 0+ | 1+ }xg ) + ( $str =~ m{ 000 | 111 | (.)\1 .* (.)\2 }x ? 2 : 0 ); print $len, "\n"; }