in reply to interpolating code in regex brace quantifier

If you have Perl version 5.10+ (update: and I see now that you use the  /r modifier on the  s/// in one of your OPed code examples, so you must have at least 5.14), the Extended Patterns  (?(condition)yes-pattern) construct where condition is  (?{ CODE }) may be of interest as it doesn't have so much scary "experimental feature" stink on it.

c:\@Work\Perl\monks>perl -wMstrict -le "use 5.010; ;; for my $s (qw(aaxyxyxy aaaxyxyxy aaaaxyxyxy)) { my $match = $s =~ m{ \b (a+) ((?: xy)+) \b (?(?{ 2 * length($1) != length($2) }) (*FAIL)) }xms; print $match ? ' ' : 'NO ', qq{match '$s'}; } " NO match 'aaxyxyxy' match 'aaaxyxyxy' NO match 'aaaaxyxyxy'
To a very limited degree, you can get away from absolute-capture numbering with tricks like this:
c:\@Work\Perl\monks>perl -wMstrict -le "use 5.010; ;; for my $s (qw(aaxyxyxy aaaxyxyxy aaaaxyxyxy)) { my $match = $s =~ m{ \b (a+) (?{ length $^N }) ((?: xy)+) \b (?(?{ 2 * $^R != length $^N }) (*FAIL)) }xms; print $match ? ' ' : 'NO ', qq{match '$s'}; } " NO match 'aaxyxyxy' match 'aaaxyxyxy' NO match 'aaaaxyxyxy'
And then there are named captures. See also Special Backtracking Control Verbs for (*FAIL).


Give a man a fish:  <%-{-{-{-<