You're mixing the scopes of your "rules" and your regular code, in that snippet - unless you really
want that (why one would eludes me, but there may be good reason I cannot think of), you will probably run into huge headaches at some point with that approach. If you don't understand why I'm saying this, then I urge you for your own sanity (and/or that of the people who will have to work with your code after you) to stick to a tried a and true solution from the CPAN.
Text::Template for example handles templates with embedded Perl code very well.
Makeshifts last the longest.