[Templates] Assign and print at the same time
Paul Seamons
mail@seamons.com
Mon, 17 Sep 2007 20:12:08 -0600
On Monday 17 September 2007, Brad Bowman wrote:
> Is there a way to assign and display a calculation in one statement?
>
> [% SGET a = 1 + 2 # set "a" to 3 and display it %]
>
> Currently I'm doing [% a = ...; a %] which is fine...
>
> Brad
Yes.
perl -e 'use Template; Template->new->process(
\"[% (a = 1 + 2) %] = [% a %]\n"
)'
3 = 3
The parens are the trick. It changes the operation from a set operation to a
GET that evaluates its statement. This is actually similar in scope to why
[% WHILE (f = f + 1) %] needs the parens.
On a further note:
This also works in Template::Alloy. Interestingly Template::Alloy also
requires the parents on self modifiers if you want the result to display:
use Template::Alloy; Template::Alloy->new->process(\"[% a+=1 %] = [% a %]\n")'
= 1
perl -e 'use Template::Alloy; Template::Alloy->new->process(\"[% (a+=1) %] =
[% a %]\n")'
1 = 1
Though Andy hasn't specified this for TT3, I think that the Template::Alloy
behavior is consistent with the current behavior of Template and is how TT3
ought to behave.
However pre and post increment should print their result immediately - which
is what Template::Alloy does.
perl -e 'use Template::Alloy; Template::Alloy->new->process(\"[% a++ %] = [%
a %]\n")'
0 = 1
perl -e 'use Template::Alloy; Template::Alloy->new->process(\"[% ++a %] = [%
a %]\n")'
1 = 1
Paul Seamons