|Perl Monk, Perl Meditation|
Here is a spoiler for #4: ok4, eval ' "(R)" =~ m(\(?r)\)?)i ';
First, capture the error that's occurring by printing the error contained in $@:
Sequence (?r...) not recognized in regex; marked by <-- HERE in m/(?r <-- HERE /
From that we see what perl (the executable) finds to be a problem: (?....) is a trigger mechanism for extended parenthesis patterns. For example, (?:...) represents a non-capturing paren. (?=...) represents a zero-width lookahead assertion. But there is no such thing as (?r...). perl doesn't know how to compile that, and generates a compile-time error. You can verify that fact by moving the regexp in question outside the eval block. The code never gets past the compile stage if you do.
But why is it that the "\(" escaped parens are not staying escaped? Ah, that's the mystery. If you change the RE from m(.....) to m/...../, the problem goes away. Double mystery? Or clue perhaps? At first I dug into perlre but quickly realized that the answer had something to do with the choice of parenthesis as quotish-delimeters, and re-focused the investigation on the Quote and Quote-Like Operators section of perlop.
There we can read the following:
Gory details of parsing quoted constructs
So what is actually happening is that when using m(...) (pairing delimiters) the \( and \) are, in the first pass, skipped as you would expect, and the actual beginning and end of the quoted material (the regex) are found properly.
But in the second pass, the \ backslash is stripped away from the inner parens, as documented. The result is that the inner parens are no longer escaped. When passed to the Regular Expression compiler, what the compiler recieves is: m/(?r)?/i. And in particular, as we saw before, (?r) is a syntax that the compiler has no idea what to do with. Thus endeth the story.