Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 999
stevendesu Avatar asked Dec 02 '22 00:12

stevendesu


2 Answers

What about fetchrow_hashref?

like image 185
Joel Berger Avatar answered Dec 18 '22 09:12

Joel Berger


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

like image 41
Bao Avatar answered Dec 18 '22 07:12

Bao