One of the coolest things to me is using Perl for code generation. Especially when it comes other languages. I have wrote several small scripts to generate C++ classes, and Java code.
Back when I was a Perl neophyte. I wrote this piece of code, that generated schema files based on our database. About 2 hours later I found out that I didn't need to do this for DBIx::Class. This is not great Perl code (don't down vote me for it. It's just an example), but it accurately generated like 200 schema files for me.
my @db = `mysql -u XXXXX -pXXXXX --skip-column-names -e "show databases;"`;
foreach my $db_name (@db) {
chomp($db_name);
my @tables = `mysql -u XXXXX -pXXXXX --skip-column-names -e "use $db_name; show tables;"`;
$_ =~ s/\n// foreach(@tables);
unless ( -e "$db_name.pm") {
open(DBFILE, '>', "$db_name.pm");
print DBFILE "package mysql::schemes::$db_name;\n";
print DBFILE "use base qw/DBIx::Class::Schema/;\n\n";
print DBFILE '__PACKAGE__->load_classes(qw/' . join(' ', @tables) . "/);\n\n";
print DBFILE "1;";
close(DBFILE);
}
mkdir $db_name unless ( -d $db_name or -e $db_name );
foreach my $table_name (@tables) {
my @columns = `mysql -u XXXX -pXXXX --skip-column-names -e "USE $db_name; desc \\\`$table_name\\\`;"`;
$_ =~ s/\n$// foreach(@columns);
my (@names, $primary_key);
foreach (@columns) {
my ($name, $type, $null, $key, $default) = split(/\t/, $_);
chomp($default);
push(@names, $name);
$primary_key = $name if($key ne '');
}
unless ( -e "$db_name/$table_name.pm" ) {
open(TBFILE, '>', "$db_name/$table_name.pm");
print TBFILE "package mysql::schemes::" . $db_name . "::" . $table_name . ";\n";
print TBFILE "use base qw/DBIx::Class/;\n\n";
print TBFILE "__PACKAGE__->load_components(qw/PK::Auto Core/);\n";
print TBFILE "__PACKAGE__->table('$table_name');\n";
print TBFILE "__PACKAGE__->add_columns(qw/" . join(' ', @names) . "/;\n";
print TBFILE "__PACKAGE__->set_primary_key('$primary_key');\n\n" unless($primary_key eq '');
print TBFILE "1;";
close(TBFILE);
}
}
}