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

Basically, I am querying a database and I need to convert the resulting 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, so lines [0] are the key and lines [1], lines [2], lines [3] are values. For each reading of the record, you must create a new hash key and set the appropriate values

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

The first record is read, and abc is the key, and numbers are the values ​​... so

+3
source share
3 answers

You can also see selectall_hashref .

$hash_ref = $dbh->selectall_hashref($statement, $key_field);
+7
source
my %hash;

while (my @fields = $sth->fetchrow_array()) {  
    $hash{$fields[0]} = [ @fields[1..$#fields] ];
}
+6
source
my %mealsizes;
my $sth = $dbw->prepare($sql);
while (@columns = $sth->fetchrow_array()) {  
  my $dayname = shift @columns;
  $mealsizes{$dayname} = [@columns];
}

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
+4

Source: https://habr.com/ru/post/1770724/


All Articles