use strict; use warnings; my $count; local $_ = " said Rabbit kindly, said Pooh humbly."; our $c = 0; / ^ (?: # Outside of brackets [^<] | # Inside of brackets < [^y>]* (?: y (?{ local $c = $c + 1 }) [^y>]* )* >? # Optional in case of unmatched bracket. )* $ (?{ $count = $c }) # Save count. /x; print("$count\n");