[% PERL %]
my @numbers = (1 .. 3);
print join(" ... ", @numbers);
[% END %]
Anything printed from within a PERL block becomes part of the final
document. PERL blocks execute under use strict, so
it pays to use lexical variables.
These lexical variables are separate from the TT2 variables like
i, the loop iterator in the earlier example. To
make a Perl value accessible to TT2 code, or vice versa, you must use
the stash. This is the TT2 symbol table, and is
accessible through the $stash variable
automatically present in PERL blocks:
[% PERL %]
my @numbers = (1 .. 3);
my $text = join(" ... ", @numbers);
$stash->set(counting => $text);
[% END %]
Here's how you count to three: [% counting %]. Wasn't that easy?
Normally you use Perl code for business logic (e.g., fetching values
from databases) and TT2 code for presentation logic (e.g., building
tables). The Perl code sets TT2 variables with the results of the
business logic (e.g., the values from the database) so that the
presentation logic has values to put into the template. In practice,
most people prefer to disable TT2EvalPerl and keep Perl code out of
their templates. this strict separation of business from presentation
logic means a customized version of Apache::Template is needed to
load the Perl code and place data in the stash.
You can initialize TT2 variables from TT2 as well:
[% text = "1 ... 2 ... 3" %] <!-- string -->
[% names = [ "Larry", "Tom", "Tim" ] %] <!-- array -->
[% language = { Larry => "Perl 6", <!-- hash -->
Tom => "Perl 5",
Tim => "Latin" } %]
[% people = { Larry => { Language => "Perl 6", <!-- nested structure -->
Town => "Mountain View" },
Tom => { Language => "Perl 5",
Town => "Boulder" } } %]
Similarly, you can fetch TT2 values from the stash:
[% FOREACH i = [1 .. 3] %]
[% PERL %]
my $number = $stash->get("i");
$stash->set(doubled => 2*$number);
[% END %]
[% doubled %] ...
[% END %]
2 ... 4 ... 6 ...
From within a PERL block, you can also use
modules. It's more efficient, however, to load the modules when
Apache starts up by replacing the PERL block's use
Some::Thing with a PerlModule
Some::Thing in httpd.conf.