Cheap Shared Hosting

Tuesday, August 5, 2008

Handy Perl Functions: get_fields()

This is the first of what may be a recurring theme - handy custom perl functions. These are custom pieces of code that I find myself using in a wide variety of places, both in dynamic websites and in maintenance scripts.

This first one is called get_fields() and its function is quite simple - it returns an array of field names for the table name passed to it. I've used it for things like generating edit/new record form templates, or when writing scripts to convert from database format to another, etc.

It uses the perl DBI module, and assumes that $dbh is the database handle that has been set up for use.

sub get_fields {
# returns array of fields for the table name passed to it
my $table = $_[0];
my (@fields, @tmp) = ();

my $qry = "describe $table";
$qry = $dbh->prepare($qry);
while (@tmp = $qry->fetchrow_array) {
push @fields, $tmp[0];
return @fields;

Feel free to use or modify at will!

No comments: