If you want to keep the logic outside the template, then use
HTML::Template. While it was originaly designed for generating HTML (as the name implies) there is nothing in it's makeup or functionality that is specificaly tied to HTML. I've used it to generate general text documents, and I can't see any reason why it couldn't be used to generate C code.