6.17.3. Discussion
The $(??{ CODE
}) construct runs the code and interpolates the string that
the code returns right back into the pattern. A simple, non-recursive
example that matches palindromes demonstrates this:
if ($word =~ /^(\w+)\w?(??{reverse $1})$/ ) {
print "$word is a palindrome.\n";
}
Consider a word like "reviver", which this pattern correctly reports
as a palindrome. The $1 variable contains
"rev" partway through the match. The optional word
character following catches the "i". Then the code
reverse $1 runs and produces
"ver", and that result is interpolated into the
pattern.
For matching something balanced, you need to recurse, which is a bit
tricker. A compiled pattern that uses (??{
CODE }) can
refer to itself. The pattern given in the Solution matches a set of
nested parentheses, however deep they may go. Given the value of
$np in that pattern, you could use it like this to
match a function call:
$text = "myfunfun(1,(2*(3+4)),5)";
$funpat = qr/\w+$np/; # $np as above
$text =~ /^$funpat$/; # Matches!