0

Using Perl and DBI to get data from SQL database. I am using the code below to get data from a table. Instead of defining 3 different arrays, is there a way to define an array with multiple fields?

$sql = "select * from tblPeople where PersonID=?";
$sth = $dbh->prepare($sql);
$sth->execute($PID);

while ($DRow = $sth->fetchrow_hashref) {
    push @KnownPIDs,  $DRow->{PersonID};
    push @Knownoss,   $DRow->{currentpos};
    push @Knownnotes, $DRow->{personnotes};
}
3
  • Please show your table schema and an example of the desired result array. Commented Jun 4, 2015 at 18:42
  • tblPeople, fields Personid, currentpos, personnotes. Not sure of the array result because I don't what is available in Perl. Commented Jun 4, 2015 at 19:24
  • Anything should be possible, if you don't know what you want how can the question be answered? Commented Jun 4, 2015 at 20:07

1 Answer 1

1

What I would do, is use the keys of the DRow hash as keys for a new HoA hash, and dynamically make each value of HoA an array.

#!/usr/bin/perl

use Data::Dumper;

my %HoA; # hash of arrays
my $DRow = {};

# set up some example data

$DRow->{PersonID} = 'steve';
$DRow->{currentpos} = 'one';
$DRow->{personnotes} = 'This is not my suicide note';

# by using a Hash of Arrays (HoA), we can dynamically build
# the entire structure without having to manually type everything 
# out for each row item

for my $key (keys(%{ $DRow })){
    push @{ $HoA{$key} }, $DRow->{$key};
}

# to access the 'PersonID' of say the third row that was processed:
# my $pid = $HoA{PersonID}->[2];

print Dumper \%HoA;

Output:

$VAR1 = {
          'personnotes' => [
                             'This is not my suicide note'
                           ],
          'PersonID' => [
                             'steve'
                        ],
          'currentpos' => [
                            'one'
                          ]
        };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.