What a great team effort! :-)
Here's the latest version. As far as I can tell this covers all the bases:
expands all backrefs (but not those in the source string), removes any
references to backrefs that don't exist, and handles escaped characters
\$ and \\. We don't worry about \1, \2, etc., because that's Old Skool
Perl and we don't support it in TT <stamp>[OFFICIALLY]</stamp>
It's based on Paul's most recent example, re-written to use a closure to
avoid the duplication, and adding Sergey's handling of escaped characters.
It passes all the tests in Sergey's test suite (which have also been
added to t/vmethod/replace.t). Not bad for 23 lines of code!
'replace' => sub {
my ($text, $pattern, $replace, $global) = @_;
$text = '' unless defined $text;
$pattern = '' unless defined $pattern;
$replace = '' unless defined $replace;
$global = 1 unless defined $global;
my $expand = sub {
my ($chunk, $start, $end) = @_;
$chunk =~ s{ \\(\\|\$) | \$ (\d+) }{
$1 ? $1
: ($2 > $#$start || $2 == 0) ? ''
: substr($text, $start->[$2], $end->[$2] - $start->[$2]);
}exg;
$chunk;
};
if ($global) {
$text =~ s{$pattern}{ &$expand($replace, [EMAIL PROTECTED], [EMAIL
PROTECTED]) }eg;
}
else {
$text =~ s{$pattern}{ &$expand($replace, , [EMAIL PROTECTED],
[EMAIL PROTECTED]) }e;
}
return $text;
},
Thanks to Paul, Nik, Sergey, Josh, Craig, and everyone else who helped to
bash this into shape. Well done guys, great work.
A
_______________________________________________
templates mailing list
[email protected]
http://lists.template-toolkit.org/mailman/listinfo/templates