The best (for some definition of that term) solution I have found for the problem of having variable numbers of caturing parens that may or may not be part of specific matches, is to use $^N, some our variables and embedded (?{code}) blocks.
our( $foo, $bar, $qux); $string =~ m[ ( some regex ) (?{ $foo = $^N }) other stuff ( a conditional capture ) (?{ $bar = $^N }) | ( another possibility ) (?{ $bar = $^N }) ... ( a final piece ) (?{ $qux = $^N }) ]x;
Using this method, you know that when the regex engine is finished, exactly where it has put whatever it has captured and you no longer have to play musical chairs trying to work it out.
With care, it is extensible to extremely complex regexes with essentially any number of captures. You can also arrange that multiple captures resulting from repeating regexes be pushed onto an array. This is something that I know of no other usable way of doing.
There is a performance penalty with this technique, and I'm not keen on the use of globals, but until we get capture-to-named-vars (which seems to be a part of P6 grammers), it is the least bad of a set of bad alternatives.
In reply to Re: Many birds, single cage...
by BrowserUk
in thread Many birds, single cage...
by monsieur_champs
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |