in reply to Re^2: Precompiling substitution regex
in thread Precompiling substitution regex

No, that's a typo. Interesting - is there a way to pass captured groups to be substituted instead of straight strings?

Replies are listed 'Best First'.
Re^4: Precompiling substitution regex
by Anonymous Monk on Jul 02, 2014 at 14:58 UTC

    Okay my stab at using captured groups as well is to use eval in the replacement evaluation, i.e.,

    foreach (@SUB_REC) { $yourText =~ s/$_->[0]/eval qq{"$_->[1]")/eg; }

    The above allows me to pass replacement strings and capture groups, e.g.,

    my @SUB_REC = map {[qr{$_->[0]}, $_->[1]]} ( ['robert|bobby', 'bob'], ['(abc)(1234)(def)', '$1$3'] );

      Using a doubled  /e regex modifier is also possible and, IMHO, better because it is simpler. (The  /e modifier can be repeated any number of times for additional 'levels' of expression evaluation.)

      c:\@Work\Perl>perl -wMstrict -le "my @SUB_REC = map [ qr{$_->[0]}, $_->[1] ], ( [ '\b(robert|bobby)\b', 'bob (not $1)' ], ) ; ;; my $yourText = 'robert dobbs and roberto jones and bobby hope'; print qq{'$yourText'}; ;; $yourText =~ s{ $_->[0] }{ qq{qq{$_->[1]}} }xmsgee for @SUB_REC; print qq{'$yourText'}; " 'robert dobbs and roberto jones and bobby hope' 'bob (not robert) dobbs and roberto jones and bob (not bobby) hope'