Rainy Day Template Fun
Randal L. Schwartz
I grew up (and still reside) in Oregon, well known for having rain nearly all
parts of the year. However, the months around April seem to have been particularly
wet, and as a child, I'd often end up doing "indoor" activities during the heaviest
rainy days.
One of the things I remember doing was playing a game (whose name I won't
mention so as not to infringe on any trademark) that consisted of two people
taking turns asking each other for various items, like "a noun" or "a verb ending
in -ed". Besides teaching us the parts of speech, it also delighted us to know
that we had constructed a story by filling in the blanks of a complete story
in an unexpected way. Of course, as we got more creative with the answers, we
got better stories.
Now, what does this have to do with Perl? Well, I often see questions online
about "how do I create a fill-in-the-blank template"? For general applications,
the answer is "go see one of the templating solutions in the CPAN". That is,
go to http://search.cpan.org and enter
template in the search box on the left. You'll see a dozen or two different
ways to take advantage of existing code.
For simple problems, though, an ad hoc approach may be best. Our story creator
software is simple enough that we can code it from scratch, also to show there's
nothing magic about the approach. Let's start with a simple template:
The [person] went to the [place].
How do we turn [person] into the question "give me a person" and put the response
back in the string? Well, something like this will work:
$_ = "The [person] went to the [place]."
|