Computer Sciences Department logo

CS 368 (Summer 2009) — Day 15 Homework

Due Friday, August 7th, at the start of class.


Write a basic template engine for something like


At the heart of your solution should be a function. It will take a string, which is an HTML template, plus a hash, which contains all of the values available for substitution into the template. The function should return the template with all substitutions made (or, say, undef, if there are requests for substitutions which do not exist in the hash). Having a function makes this very testable! Anyway, a call to your subroutine might look like this:

my $html = fill_template($template, %values);

The template should consist of HTML, plus special “tags” that tell your template engine to substitute a value. The special tags will start with <% and end with %>. So, for example, here is a fragment of a template:

<p>Hello, <% name %>!</p>

In that case, if the hash contains the key “name”, then the corresponding value will be substituted in place of the entire <% name %> string, resulting in a return value something like this:

<p>Hello, Tim!</p>

Demonstrate that your function works. I do not expect you to set up a CGI environment, or even to try to use Instead, simply hardcode a template and a substitution hash into your script, run the function on them, and print the results. Or, if you like, write test cases. Or both. But do something to show that you understand how to call your function and use its results.

Super Bonus: If you really want to think hard about a central problem of writing a web framework, try to make your function cope with simple expressions in the substitution tags, not just trivial variable interpolation. So for example, could you make your function deal with this:

<p>The answer is <% total + bonus %></p>

Or how about statements?

<% if (list_size > 0) { %>
<p><% join(', ', list) %></p>
<% } %>

Just to be clear: By bonus, we mean extra edification and valuable learning; we do not mean extra points.


Do the work yourself, consulting reasonable reference materials as needed; any reference material that gives you a complete or nearly complete solution to this problem or a similar one is not OK to use. Asking the instructors for help is OK, asking other students for help is not.

For what it’s worth, it has taken me far more lines of text to describe this problem than it took me lines of Perl (about 25, for the record) to code the solution. Of course, I know lots of Perl tricks, but still, the point is that this is fairly easy to code in Perl.

Hand In

A printout of your script on a single sheet of paper. At the top of the printout, please include “CS 368 Summer 2009”, your name, and “Homework 14, August 4, 2009”. Identifying your work is important, or you may not receive appropriate credit.