in reply to Precompiling substitution regex

You can interpolate precompiled regexes into substitutions as well. The different modifiers can go into each regex:
my @SUB_REC = ( qr{(?:this|or|that)}si, qr{(?:One|Two|Three)}s, ); my @SUBSTITUTION = qw/bob four/; for my $idx (0..$#SUB_REC) { $str =~ s/$SUB_REC[$idx]/$SUBSTITUTION[$idx]/; }

Replies are listed 'Best First'.
Re^2: Precompiling substitution regex
by FreakyGreenLeaky (Sexton) on Jun 17, 2011 at 11:57 UTC
    Thanks moritz, that will work. Is there any way of achieving that without having the substitutions in a separate array?
      Well, you could of course store an array of closures that each does a substitution, and call those in turn - but it might slow down things again. Or you could store regexes and substitutions in the same array, but distinguished by different indexes (even/odd or first half/second half).

      But I don't think you can easily store a precompiled whole substitution in a single scalar.

        ... store regexes and substitutions in the same array, but distinguished by different indexes ...

        An example of what I think moritz is referring to (and the way I think I would approach the problem):

        >perl -wMstrict -le "my @subs = ( [ qr{ (?i) foo | bar }xms => 'quux' ], [ qr{ fee | fie | foe }xms => 'fum' ], ); ;; my $string = 'foo fee BAR foe fOo fie FOE'; for my $ar_sub (@subs) { my ($search, $replace) = @$ar_sub; $string =~ s{$search}{$replace}g; } print qq{'$string'}; " 'quux fum quux fum quux fum FOE'

        Note that regex modifiers like /g cannot be associated with each individual regex using this approach; something a little more fancy is needed for that.