tags:

views:

112

answers:

3

Basically, I'm querying a database and I need to convert the resultant array to a hash.

I query the database as follows

my $sth = $dbw->prepare($sql);
while (@rows = $sth->fetchrow_array()) {  
...
...
}

Now, I need to create a hash such that rows[0] is the key and rows[1],rows[2],rows[3] are the values. For each record read, a new hash key has to be generated and the corresponding values set

If my tables look like

abc 2.3 2.4 2.5
def 3.2 3.3 3.4
ijk 4.5 4.6 4.7

First record is read and abc is the key and the numbers are the values...so on

+6  A: 
my %hash;

while (my @fields = $sth->fetchrow_array()) {  
    $hash{$fields[0]} = [ @fields[1..$#fields] ];
}
eugene y
How does the hash look in this case? Is it like `$rows[0] => @var`
Aks
@Aks: hash values are scalars. So it is `$rows[0] => \@var`
eugene y
I'm sorry. I dont know what \@ means
Aks
@Aks: it's a reference to array. See http://perldoc.perl.org/perlref.html
eugene y
ok.great.thanks
Aks
Don't name your variable `@rows`, it only contains one row at a time, so call it `@row`.
mscha
+4  A: 
my %mealsizes;
my $sth = $dbw->prepare($sql);
while (@columns = $sth->fetchrow_array()) {  
  my $dayname = shift @columns;
  $mealsizes{$dayname} = [@columns];
}

Here's an illustration of constructing and using an arrayref.

#!/usr/bin/perl
#
use strict;
use warnings;

my %h;
while (<DATA>) {
  my @columns = split;
  my $k = shift @columns;
  $h{$k} = [@columns];
}

for my $k (sort keys %h) {
  print "$k => ", join(', ', @{$h{$k}}), "\n";
}

__DATA__
abc 2.3 2.4 2.5
def 3.2 3.3 3.4
ijk 4.5 4.6 4.7
RedGrittyBrick
+8  A: 

You could also have a look at selectall_hashref.

$hash_ref = $dbh->selectall_hashref($statement, $key_field);
M42
@downvoter: could you explain why ?
M42
I'm not the downvoter you addressed that comment to, but this doesn't answer the question asked.
Kinopiko
@Kinopiko: for me this gives an hashref containing retrieved rows indexed by a key, that is what the OP wants or i'm missing something.
M42
@M42: I assumed that the poster wanted to have an array containing the values from each row rather than a hash reference.
Kinopiko