my @strings = qw( aaabbbb ab abb aabb aaabb aabbb ); my $a_counter; my $b_counter; for my $string ( @strings ) { print "In $string there were $a_counter 'a's and $b_counter 'b's.\n" if ( $string =~ /(a(?{$a_counter ++; } ))+(b(?{$b_counter ++;}))+/ ); } #### In aaabbbb there were 3 'a's and 4 'b's. In ab there were 4 'a's and 5 'b's. In abb there were 5 'a's and 7 'b's. In aabb there were 7 'a's and 9 'b's. In aaabb there were 10 'a's and 11 'b's. In aabbb there were 12 'a's and 14 'b's.