http://www.perlmonks.org?node_id=350067


in reply to Explained: Trying to count the captures in a compiled regular expression
in thread Trying to count the captures in a compiled regular expression

That runs in scalar context, so won't work; try:
$matches = (() = /($regex)??/) - 1;