Joerg, Harald wrote:
> It is not so easy to get $1 to work in the way required here
> with the replace SCALAR_OP since perl does only one
> level of variable interpolation.
Yes, it's a tricky one. There's a couple of items in the TODO list
which read:
* Richard Tietjen's patch for stash replace. Allows back references
(e.g. $1) but it would be nice to find a rock-solid way to implement
it without relying on unusual ^A delimiter character.
* Further to the above, Craig Barratt has this solution which will be
going into the next verion (2.05b) unless anyone has any further
suggestions to make before then.
It would be great if replace handled backreferences. I don't like
the ^A solution since the string could contain ^A, plus it is a
security hole. The attempt I posted only works for up to 9
backreferences and doesn't handle an escaped '\$' and uses nested
evals:
$str =~ s{$search}{
my $r = $replace;
my @d = (0, $1, $2, $3, $4, $5, $6, $7, $8, $9);
$r =~ s/\$(\d+)/$d[$1]/eg;
$r;
}eg;
I wish there was a perl predefined variable array containing all
the backreferences (is there one?). You can avoid the hard-coded
limit of 9 with extra evals, and a bit of work on the re could
handle the escaped '\$' case, so maybe that would be good enough.
I obviously didn't put it into 2.05b like I said I would (mea culpa)
but I'm happy for it to go in now. I don't think there is an array
containing all the backrefs in Perl, or even a variable which tells
you how many matches matched. Does anyone else have any ideas how
you might find out?
I'd also like a 'matches' method that returns a reference to a list
of the matches. That would allow you to do things like this:
[% string.matches('(.).*').0 %] # first character
or:
[% matches = string.matches('(\w+)\s+(\w+)') %]
first word: [% matches.0 %]
second word: [% matches.1 %]
and so on.
A