in reply to Backref in a regex quantifier

I can't tell you why the backref doesn't work in a quantifier... but you could use the "postponed regex" construct (??{ code }):

my ($n, $v) = "3 aaa " =~ /^(\d+?) ((??{".{$1}"})) /; print "n=$n, v=$v\n"; # prints "n=3, v=aaa"

Replies are listed 'Best First'.
Re^2: Backref in a regex quantifier
by Anonymous Monk on Jul 09, 2007 at 19:58 UTC
    a small tweak would be to use the  $^N pre-defined variable that "contains whatever was matched by the most-recently closed group (submatch)".
    this makes the sub-expression less sensitive to its position in a possibly complex regex expression.

    perl -wMstrict -e "my $re = qr/ ^ (\d+?) ( (??{ qq(.{$^N}) }) ) /x; /$re/, print qq($_ [$1] [$2] \n) for @ARGV" 43fffxxx 54321234 12xxxxxxxxxxx 12xxxxxxxxxxxx 43fffxxx [4] [3fff] 54321234 [5] [43212] 12xxxxxxxxxxx [1] [2] 12xxxxxxxxxxxx [1] [2]