in reply to Re: $1 in variable regex replacement string
in thread $1 in variable regex replacement string

To Joey The Saint -- sadly, I do not think the answer lies in the direction you suggest.

The problem is that $pat and $repl come as shown to the routine in question from elsewhere. (The code above is, of course, a reduced demo to focus on the problem.) The contents of $1, $2, etc. (if any) are not known until $pat is invoked here, so I do not see an obvious and practical way to *pre*-load the regex vars in $repl using double-quotish behavior. The substitution must be done *after* $repl comes to this routine.

I did travel a little way down the following path:

#!/usr/bin/perl -w use strict; my $str = 'abcadefaghi'; my $pat = '(a.)'; my $repl = '\u$1 '; $str =~ s/$pat/ my @save = (undef, $1, $2, $3, $4, $5, $6); $repl =~ s{\$$_}{$save[$_]}g for 1..6; $repl; /eg; print "$str\n";
...and that works for the '$1'-type vars without opening up the eval danger. The problem is that this approach then leaves me with having to write more similar code to handle all other special chars (e.g. '\u' as shown) with similar hand-coded replacements. Safe but yucky.