The reason (?{}) and (??{}) aren't used to often is that they are extremely powerful, and most data parsing simply doesn't need that kind of power (or, when it does, most people will turn to Parse::RecDescent). However, I've found the code expression abilty to be quite helpful in employing a few slick tricks, such as:
Conditional Insert: (??{(cond) ? yes : no})
I'm not talking about (?(cond) yes|no), of course; (?(cond) yes|no) will only take a backreference or a zero width assertion as its condition. (??{(cond) ? yes : no}) will similary cause the appropriate pattern to be inserted based on the evaluation of the condition; however, the condition is no longer limited. This is useful in such cases where you don't want to fail if are using the (?(cond)yes) of (?cond), or are mucking with much weirder other things... (see my homenode for an example)
Partial Backreferences: (??{substr($string_that_is_matched_against,$+[$#+]-1,1)})
The snippet above will insert the last character was matched when the regex hits that point. Above is a general case, useful if you are playing with recursion; if you know $DIGIT, you can always do:
(??{substr($DIGIT,-1)}
Dynamically Building Character Classes: (??{'[\Q$letters\E]*'})
Variables normally can't be interpolated within character classes. With (??{}), now you can.
Matching/extracting arbitrarily nested elements with recursion: (??{$compiled_regex})
Like the anonymous monk already said, (??{}) is a necessity in matching nested sets of paren/brackets/etc if you don't want to go crawling through the string C-style. I go into more detail using a less basic example than the one in perlre here.
I have other "interesting" regex on my homenode, and many involve our friends (??{}) and (?{}). Take a look if you don't feel like sleeping well tonight.
In reply to Re: Useful Uses of regex code expressions?
by jryan
in thread Useful Uses of regex code expressions?
by kvale
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |