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");

0 responses to 'Neat Perl DBI features'

Showing last 0 comments... (Click here to view all comments)


Leave a reply

You need javascript enabled to use this form. Anti-spam efforts ongoing. Also, if the comment doesn't show up, it's because the form expired. Go back and copy your comment, reload the form, and resubmit. Apologies if this is a hassle, I'm just playing with antispam methods right now. If this insists on not working, please email me about it.

Name (required)
E-mail (optional, if you want me to be able to email you back)
URL (also optional)
Comment: