在您的情况下,您不需要嵌套循环。
将您的模板文件更改为:
<table>
<TMPL_LOOP dogs>
<tr><td> </td><td></td><td></td><td></td><td></td><td></td></tr>
<tr>
<td></td><td>Name</td>
<td></td><td>Start</td>
<td></td><td>End</td>
</tr>
<tr>
<td><TMPL_VAR ldogname></td><td><TMPL_VAR dogname></td>
<td><TMPL_VAR lstart></td><td><TMPL_VAR start></td>
<td><TMPL_VAR lend></td><td><TMPL_VAR end></td>
</tr>
<tr>
<td><TMPL_VAR lbreed></td><td><TMPL_VAR breed></td>
<td><TMPL_VAR lsex></td><td><TMPL_VAR sex></td>
<td><TMPL_VAR lcolor></td><td><TMPL_VAR color></td>
</tr>
<tr>
<td><TMPL_VAR leye></td><td><TMPL_VAR eye></td>
<td><TMPL_VAR lweight></td><td><TMPL_VAR weight></td>
<td><TMPL_VAR lattr></td><td><TMPL_VAR attr></td>
</tr>
</TMPL_LOOP>
</table>
和你的代码:
#!/usr/bin/perl
use warnings;
use strict;
use HTML::Template;
my $template=HTML::Template->new(filename=>'template.txt');
my @dogs=( #dogs data
{dogname=>'Dog',start=>'04-02-1996',end=>'06-19-2011',breed=>'Terrier',sex=>'Male',color=>'Brown',eye=>'Green',weight=>'10 Pounds',attr=>'bla bla'},
{dogname=>'Dog',start=>'03-04-1985',end=>'06-01-1988',breed=>'Retriever',sex=>'Female',color=>'Black',eye=>'Green',weight=>'50 Pounds',attr=>'bla bla'},
);
my %labels=(
ldogname=>'',
lstart=>'',
lend=>'',
lbreed=>'Breed: ',
lsex=>'Sex: ',
lcolor=>'Color: ',
leye=>'Eye Color: ',
lweight=>'Weight: ',
lattr=>'Attribute: '
);
for my $dog (@dogs) { #mix labels and values
while (my ($k,$v)=each %labels) {
$dog->{$k}=$v;
}
}
$template->param(dogs=>\@dogs);
print $template->output;
您将获得所需的输出。
但要回答您的问题,您可以查看一些嵌套循环的示例:http ://www.perlmonks.org/?node_id=770278 http://www.perlmonks.org/?node_id=193367(谷歌返回更多结果)