E R wrote:
> Having the .match() and .replace() virtual methods is nice, but it
> would be very convenient to have a 'destructive' substitute operator
> which performs a regex substitution on a variable and returns true if
> the substitution was performed and false otherwise.
>
> For instance, a lot of validation+cleanup code can be written with
> perl's s{}{} operator, e.g.:
>
> # accept a number with possible leading and trailing whitespace:
>
> if ($input =~ s{\A\s*(\d+)\s*\z}{$1}) {
> # input is a valid number and $input is the cleaned-up number
> } else {
> # input is not valid
> }
>
> And it would be nice to be able to do this in TT. Is this already possible?
The problem here is needing a reference to the original stash item to work on.
As a random test I figured I might be able to use Perls @_ parameter aliases to
do this.
TT Code:
-----------------------------------------------------
[% foo = 'hello test test' %]
Number of replacements: [% foo.inplace() %]<br>
foo is now: [% foo %]
-----------------------------------------------------
Vmethod Code:
-----------------------------------------------------
$Template::Stash::SCALAR_OPS->{inplace} = sub {
# use direct operation on original passed in variable $_[0]
return scalar($_[0] =~ s/test/hi/g);
};
-----------------------------------------------------
Interestingly, this seems to work for me with the XS stash, but not the regular
stash.
XS Stash output:
-----------------------------------------------------
Number of replacements: 2
foo is now: hello hi hi
-----------------------------------------------------
Perl Stash:
-----------------------------------------------------
Number of replacements: 2
foo is now: hello test test
-----------------------------------------------------
It probably would actually be pretty useful if we could allow this kind of
reference replacement in the vmethods, but I don't have time to look at the
Perl stash and see if that's feasible.
-- Josh
_______________________________________________
templates mailing list
[email protected]
http://mail.template-toolkit.org/mailman/listinfo/templates