http://qs321.pair.com?node_id=349794

This subroutines count the number of capturing parentheses in a compiled regular expression. Since the regexp is compiled, we know it's correct, and thus we only have to count the opening parentheses.

Update: added /s in the while condition.

Update: This other discussion led to a much better solution, so I commented out the original code.

#sub captures { # local $_ = shift; # croak "$_ is not a compiled regexp" unless ref eq 'Regexp'; # my $n = 0; # while( /\G(?=.)/gcs ) { # /\G[^\\(]*/gc; # ignore uninteresting stuff # /\G(?:\\.)*/gc; # ignore backslashed stuff # /\G\(\?/gc; # ignore special regexps # /\G\(/gc && $n++; # a capturing (, count it! # } # $n; #} sub captures { ( @_ = '' =~ /(@{[shift]})??/ ) - 1; }