On Wed, Dec 26, 2012 at 04:10:06PM +0100, gator...@yahoo.de wrote: > Hi, > > I would like to store regular expressions and substitution strings in > a hash variable. If a given string matches any of the stored patterns, > the corresponding substitution should be applied. What originally looked > trivial turned out to be quite a challenge, particularly if the > substitution string contains references to capture buffers. > > Here's a minimal example: > > my $rx=qr/^aaaa_(.*)/; > my $r='a_$1'; > my $s="aaaa_bla_fasel_blub"; > if ($s=~ /$rx/) { # pattern matches, apply substitution if you can > # hardcoded, it's trivial: > # $s =~ s/$rx/a_$1/; > # but how to interpolate the capture buffer? Not like this: > # eval '$s="$r"'; > # eval { $s=$r }; > # $s =~ s/$rx/$r/e; > } > > Can anybody think of a straightforward way to do this?
This is a situation where string eval is warranted: eval "\$s =~ s/\$rx/$r/"; Three points: - make sure you trust your input - be sure to check $@ - there's no need to check if the pattern matches first, just attempt the substitution -- Paul Johnson - p...@pjcj.net http://www.pjcj.net -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/