Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re (tilly) 1: Code that writes code

by tilly (Archbishop)
on Dec 23, 2000 at 04:06 UTC ( #48112=note: print w/replies, xml ) Need Help??


in reply to Code that writes code

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.

  1. 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 interpret it...hrm...)
  2. 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.
  3. 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.
  4. 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.)
  5. 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 while thinking about how much it looks like having code that writes code.

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.. :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://48112]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2020-07-12 08:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?