Hooray for HTML::Template

Don't do a lot of programming-blogging here, but I thought I'd mention a recent overhaul of the script that generates the very page you're currently reading. Folks with no interest in Perl or web programming should probably move on.

It involved converting from the original plain old CGI script (using Lincoln Stein's famous CGI.pm) to use of the HTML::Template Perl module. Briefly, HTML::Template allows you to factor out the HTML structure of your web page into a template file; your Perl code then simply (heh!) "fills in the blanks" in the template, then blasts out the resulting page to you, dear reader.

Don't see any difference in the blog? That's the idea.

The instructive metric is (probably) total code size.

Old CGI script:
297 lines, 8334 bytes
New CGI script:
213 lines, 6541 bytes
New Template:
120 lines, 3050 bytes
So, instead of one file, we have two. But the total size of the two new files is only slightly bigger than the size of the old CGI script. (12% bigger, measured in lines; 15% bigger, measured in bytes). That's a pretty modest cost, given that (I think) the result is easily more maintainable.

The slight downside is that you have to keep your template tag names consistent between the Perl code and your template. No big deal. (Or shouldn't be a big deal for a disciplined coder; for me, on the other hand … fortunately, the generated error messages are clear and not too insulting.)

The major time taken in the conversion was that dippy little month calendar over there on the right. This required nested template loops, with an associated nested Perl data structure constructed in the script. My brain hurt badly afterwards; it didn't help that the official documentation was kind of weak on this point. Fortunately, the Google allowed me to find a Linux Gazette article where some brilliant hacker, Ben Okopnik, had figured it out.

I am, admittedly, a latecomer looking at HTML::Template, but in case you find yourself spending a little too much time trying to maintain HTML-generating Perl code, you might want to check it out.