http://qs321.pair.com?node_id=48060

I was reading through some suggestions on good coding practice when I came across the following:

Write Code That Writes Code

Code generators increase your productivity and help avoid duplication.

This makes sense, but I have had limited experience with it. For example, I once stumbled across the following bit of code:
if ($main::stateIn{'sibling'}) { no strict 'refs'; &{$main::stateIn{'sibling'}}(); }
This code allowed the programmers to simply name a "sibling" in a hidden field of Web pages and have the target CGI script call the appropriate subroutine based upon the sibling. This code actually opened up some significant security issues and was replicated throughout many scripts. Since there were quite a number of these scripts, and most of these scripts had quite a number of subroutines that could be called, recoding these by hand was likely to be tedious and error-prone.

To deal with this, I wrote the following program (which relies on my knowledge of our programming practices -- it's not likely to be portable):

#!C:/perl/bin/perl.exe -w use strict; open INV, "<$ARGV[0]" or die $!; open OUT, ">out.txt" or die $!; print OUT "SWITCH: {\n if ( defined \$sibling ) {\n"; while ( <INV> ) { if ( /^\s*sub\s+([a-zA-Z][^\s{]+)/ ) { next if $1 eq 'AUTOLOAD' or $1 eq 'main'; print OUT " if ( \$sibling eq '$1' ) { &$1; last SWITCH + };\n"; } } print OUT "\n\n &main;\n last SWITCH;\n }\n"; close INV; close OUT;
Essentially, every time I was converting a program, I would run this snippet and it would produce an output file similar to the following:
SWITCH: { if ( defined $sibling ) { if ( $sibling eq 'uFMProducts' ) { &uFMProducts; last SWITCH } +; if ( $sibling eq 'catalogDealerProducts' ) { &catalogDealerPro +ducts; last SWITCH }; if ( $sibling eq 'prodByCatalog' ) { &prodByCatalog; last SWIT +CH }; if ( $sibling eq 'catalogProductView' ) { &catalogProductView; + last SWITCH }; if ( $sibling eq 'catalogProductUpdate' ) { &catalogProductUpd +ate; last SWITCH }; if ( $sibling eq 'dealerProducts' ) { &dealerProducts; last SW +ITCH }; if ( $sibling eq 'categoryDetail' ) { &categoryDetail; last SW +ITCH }; if ( $sibling eq 'prodByCategory' ) { &prodByCategory; last SW +ITCH }; . . . &main; last SWITCH; }
Much better. While I had some manual clean-up to do pruning out subs that shouldn't be called directly, I had taken a long, tedious task and reduced it to a couple of minutes of work and closed a significant security hole.

Aside from a few other limited examples, this is the extent of my "code from code". I am curious as to how other Monks have used "code from code" and what examples they might be able to provide. I have limited experience in this area and am excited about the possibility of learning more.

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.