Search this site


Metadata

Articles

Projects

Presentations

Neat Perl DBI features

Something I'd never bothered doing is reading perldoc DBI. I was looking through it today looking for a function I forgot the name of and I ran across a function, selectall_hashref. This thing is *totally* sweet. It takes a SQL query and a key field as arguments. It then puts all the results into a hash with the "key field" as the hash key. I never knew about this until now. If you're still at a loss for what it saves you, here's what it shortens:

my $db = DBI->connect(...);

my $res = $db->preprae("SELECT * FROM foo");
$res->execute();

my $foo;
while (my $hr = $res->fetchrow_hashref()) {
	$foo->{$hr->{"id"}} = $hr;
}

And using selectall_hashref instead:

my $db = DBI->connect(...);

my $foo = $db->selectall_hashref("SELECT * FROM foo", "id");