I have done this, and recommend it with warnings. The
main problem is that you are creating a layer of indirection
between you and the problem. This makes it harder to figure
how how you should do the problem. But when you get the
solution, the solutions tend to be better.
There are many basic approaches that I have used. Each
has advantages and disadvantages.
- You can write a little macro language which is turned
into code and evalled. Damian Conway is fond of this
approach. See for a random example, Class::Contract.
Generally this takes a lot of work to do, and involves
creating a macro language. But the result can be very
powerful. (Usually I just use some subset of Perl as my
macro language and use do or eval to parse and
- You may have boiler-plate code to insert in appropriate
places. See, for instance, AbstractClass. Outside of
very rigid problems, this approach makes symbolic
references look downright sane.
- Your use of text manipulations to make code in one
form turn into another is common. Particularly for
mass edits, obfuscating code, so on and so forth.
- Turning data structures into code and back is often
very useful. See Data::Dumper. (I have used similar
techniques to freeze data structures in one language and
re-instantiate them in another.)
- Often a large and complex script can be maintained as
an auto-generated thing from a number of small ones
through some sort of template. Perl's Configure shell
script is maintained this way. Take a look at the make
utility for some ideas on how to do that.
Another key insight that may help is that a lot of
functional techniques do the same thing as automatic
code generation in a more controlled way. For instance in
a similar situation to yours I might use a
hash of subs
. you can build up a complex
regular expression using qr//. Turning "templates" of
functions into real functions can be done with closures.
You may want to take another gander at Why I like functional programming
thinking about how much it looks like having code that
Hopefully this should give you some ideas for how to use
automatic code generation, and a few places to look for
examples of it being done.. :-)