use HTML::Template; # ... first send header, update counters, whatever ... # then comes HTML rendering phase: my $template = HTML::Template->new('template.html'); # set some parameter $template->param('counter', $counter); # print it all print $template->output();