开发者

In Perl, how can I convert arrays I read from database into a hash?

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


You could also have a look at selectall_hashref.

$hash_ref = $dbh->selectall_hashref($statement, $key_field);


my %hash;

while (my @fields = $sth->fetchrow_array()) {  
    $hash{$fields[0]} = [ @fields[1..$#fields] ];
}


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜