in reply to Precompiling substitution regex

Newbie to Perl, but just found myself in similar circumstances. For what it's worth, I'm using a two dimensional array with map, i.e.,

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

where the first element of each row is the regex and the second element is the substitution. Then simply use

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

Obviously you can add more elements to the array for flags.

Replies are listed 'Best First'.
Re^2: Precompiling substitution regex
by AnomalousMonk (Archbishop) on Jul 02, 2014 at 13:42 UTC
    ['(robert|bobby)', 'bob']

    Your example regex has a capture group, but the subsequent substitution doesn't seem to offer any opportunity to use what was captured. Is there any reason for capturing?

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

        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'] );
Re^2: Precompiling substitution regex
by Anonymous Monk on Jul 26, 2019 at 06:02 UTC
    Looping misses the point of the other answers, which is to execute just one regex that matches all the patterns.