Home Ask Login Register

Developers Planet

Your answer is one click away!

Tobias J. February 2016

How to exit a tmpl loop in perl?

I use html templates in Perl to generate a dynamic website, my Script1.pm generates a table and sends it as tmpl_loop to the template.tmpl to show a table on the website.

This works pretty well so far, but as the table gets bigger than about 100,000 rows, the whole browser starts to lag.

Can I somehow set a counter to exit the tmpl loop after 10000 iterations?

Just making the table smaller in the script doesn't work cause I need it completed for an export file.


ikegami February 2016

Trim the data before sending it to the template in the first place.

For example, change

 $template->param(ROWS => \@rows);


 splice(@rows, 10_000);
 $template->param(ROWS => \@rows);


 my @truncated_rows = @rows[0 .. $#rows < 10_000 ? $#rows : 10_000];
 $template->param(ROWS => \@truncated_rows);

The latter is non-destructive, so if you need the entire set of rows for another purpose later in the program, they will still be available. (It seems fishy to continue processing after the output is rendered, but an update to the question seems to indicate this is a requirement.)

oalders February 2016

If you're using Template::Toolkit, you can use the special loop variable:

[% FOREACH match IN results %]
    [% LAST IF loop.count > 10000 %]
[% END %]

Note that BREAK is also an alias for LAST.

Post Status

Asked in February 2016
Viewed 2,078 times
Voted 12
Answered 2 times


Leave an answer

Quote of the day: live life