The others have already given you some ideas for better parsing. However, you're mistaken on the premise of the question:
It then occurred to me that the code won't run if the regexp has no capture groups! ... I need the captures.
The code will still run - a regex in list context without /g and without capture groups will return the list (1) if it matched, so the assignment will evaluate to true. See also.
use warnings; use strict; use Data::Dump; my @syntax = ( [qr/cd/, sub { dd "callback", \@_ }] ); my $line = "abcdef"; for my $syn (@syntax) { my ($re, $cb) = @$syn; if (my (@matches) = ($line =~ $re)) { $cb->(@matches); last; } } __END__ ("callback", [1])
Update: And $#+ will give you the number of capture groups present in the last successful match (see also).
In reply to Re: How to know that a regexp matched, and get its capture groups? (updated)
by haukex
in thread How to know that a regexp matched, and get its capture groups?
by Anonymous Monk
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |