my $bracketlevel = 0;
my $s2 = "((()))(())(()";
$s2~~s:g/(()|(')')/{ 

if defined $0 { say "0: $0"; ($bracketlevel++ X " ") ~"("   } 

if defined $1 { say "1";  }

}/;

Add a code snippet to your website: www.paste.org