untitled

(ff) #1

250 10 Transforming with Traditional Programming Languages


use Template;

while (<>) {
chomp;
split(/:/);
$name = $_[0];
$content = $_[1];
}
$tt = new Template;
$vars = {
name => $name,
content => $content,
};
$tt->process(’part.tt’, $vars);

Program 10.21 Using Perl templates

Now consider a more interesting transformation task: the first task of this
chapter. To use a Perl template, the data extracted from the input file must
be organized into a data structure to be used by the template processor for
instantiating the template as in program 10.22. Thewhilestatement con-
structs an array of hashes. Each hash gives the information about one inter-
view of the health study. In other words, each hash represents one record of
the health study database. The template processor is given this array in the
same way as in the earlier program, except that now there is just one hash
key:HealthStudyInterviews. This will be the name of the array within
the template. The template is shown in template 10.2. Notice that one iter-
ates over the elements of the array in almost the same way as in Perl. The
Template Toolkit, however, uses a more simplified notation than Perl:


  1. Variables usually have no initial character such as%[email protected]
    Toolkit does use the$but only when one is substituting a value in an
    expression. For example, if one has a variable namedstatuswhose
    value is “obese,” then the expressioni.statuswould have two different
    meanings. Should it mean$i{status}or should it mean$i{obese}?
    In the Template Toolkit one specifies the second one by writingi.$sta-
    tus. The $ prefix in the Template Toolkit means “substitute the value of
    the variable here.”

Free download pdf