I'm trying to use perl Text::Template for short templates and so far failed to get it to iterate over an array.
Here is a short test program I wrote to demonstrate what I'm trying to do:
#!/usr/bin/perl
use Text::Template;
my $template = Text::Template->new(TYPE => 'STRING', SOURCE => <<'__EOT__');
array[0]: { $array[0] }
{ foreach my $i (@array) { }
{$i}
}
__EOT__
print $template->fill_in(HASH => { array => [qw(item1 item2)]});
According to the Text::Template manual I expected this to print: array[0]: item1 item1 item2 But instead it prints array[0]: item1
(i.e. the output of the first line outside the loop and an empty line).
I couldn't find anywhere on the web any example of someone actually using a loop inside a template, though the documentation says it should "just work".
What am I missing?
A couple of experiments indicate that this:
Is turned into (effectively) something like this pseudo-perl:
So the "stuff" needs to be an expression so that it returns something to put into the template. Your "stuff" is a
foreach
loop which doesn't have a value so your template doesn't do anything interesting.If you look at the tests for
Text::Template
(always go to the test suite for examples, the test suites for CPAN packages are invaluable for learning how things work), you'll see things like this:Note the way
$t
is being used. That indicates that you want something more like this for your template:There's also the
$OUT
special variable which can take the place of$t
above. The documentation for CPAN packages is generally pretty good and well worth reading, you'll miss it when you work in other languages.