in reply to Database field names in code

For me, it's generally not a matter of hard coding the field names, but limiting the amount i do. When retrieving data for display, i strive to only "hard code" my database field names in 2 places ... the SQL query and the template (usually HTML). I discuss more of that in a moment, but for now, know that DBI allows you to deal with the query results in a variety of useful ways. You really should become familar with the documentation and then have a look into Class::DBI. For example, try this code on one of your SELECT queries:

use DBI; use Data::Dumper; my $dbh = DBI->connect( ... ); # Example 1: List of Lists print Dumper $dbh->selectall_arrayref('select id,name from status'); # Example 2: List of Hashes print Dumper $dbh->selectall_arrayref( 'select id,name from status', { Slice=>{} }, );
And pay close attention to the results. The first is really just a two dimensional table, like a spreadsheet without headers. Here is what my results yield:
$VAR1 = [
          [
            '0',
            'enrolled'
          ],
          [
            '1',
            'dropped'
          ]
        ];
With this, i can now build a useful hash with which i can lookup values if need be ... but notice that i only specify the field names in the SQL query (and that i reversed them from the last example):
my $rslt = $dbh->selectall_arrayref('select name,id from status'); my %hash = map @$_, @$rslt; print Dumper \%hash;

But what about the second example, the one with the strange and cryptic { Slice => {} }? For a web developer who has to build reports and such, that is one of the best things since sliced bread. With this, i need only specify which fields i want in the SQL query, and then once more in the template. Here is an example that uses an easy to install CPAN module, HTML::Template. Just run the code first, you can ask more questions later. :)

use DBI; use HTML::Template; my $dbh = DBI->connect( qw(DBI:vendor:database:host user pass), {RaiseError=>1}, ); my $things = $dbh->selectall_arrayref(' SELECT id,name FROM status ',{Slice=>{}}); # optionally do more things to some of the fields # yes, we do have to say their names again $_->{id} = sprintf("%03d",$_->{id}) for @$things; my $tmpl = HTML::Template->new(filehandle => \*DATA); $tmpl->param(things => $things); print $tmpl->output; __DATA__ <tmpl_loop things> <tmpl_var id>: <tmpl_var name> </tmpl_loop>

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)