stevendesu
stevendesu

Reputation: 16771

Returning MySQL results as hash tables in Perl

In Perl I'm making an SQL query akin to the following:

SELECT `id`, `title`, `price` FROM `gamelist`

What I wish to do is take the result of this query and dump it into a hash table. I am using DBI and currently I only know how to do the following:

my %results;
my $count = 0;
while( @result = $statement->fetchrow() ){
    %results{'id'}[$count] = $result[0];
    %results{'title'}[$count] = $result[1];
    %results{'price'}[$count] = $result[2];
    $count++;
}

However I don't like using $result[0] and trusting that the first field will be the ID. I would much rather have something like:

my %results;
my $count = 0;
while( %result = $statement->fetchrow_as_hashtable() ){
    %results{'id'}[$count] = %result{'id'};
    %results{'title'}[$count] = %result{'title'};
    %results{'price'}[$count] = %result{'price'};
    $count++;
}

I tried looking around on Google but couldn't find many good answers built into DBI/Perl. I did find an open-source class that offered this functionality, but I feel like this should be possible without the use of someone else's class.

Upvotes: 4

Views: 9131

Answers (3)

Bao
Bao

Reputation: 326

while (my $result = $statement->fetchrow_hashref) {
        print $result->{id};
        print $result->{title};
        print $result->{price};
}

Use fetchrow_hashref to have the result directly in a hash

Upvotes: 5

Joel Berger
Joel Berger

Reputation: 20280

What about fetchrow_hashref?

Upvotes: 9

ErikR
ErikR

Reputation: 52029

Consult the DBI documentation for this use of selectall_arrayref:

 $rows = $dbh->selectall_arrayref($query, {Slice=>{}}, @params)

$rows is an Array of Hashes.

Upvotes: 4

Related Questions