使用Perl和DBI从SQL数据库中获取数据。我使用下面的代码从表中获取数据。而不是定义3个不同的数组,有没有办法定义一个包含多个字段的数组?
$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};
}
答案 0 :(得分:1)
我会做的是使用DRow哈希的键作为新HoA哈希的键,并动态地使HoA的每个值成为一个数组。
#!/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;
输出:
$VAR1 = {
'personnotes' => [
'This is not my suicide note'
],
'PersonID' => [
'steve'
],
'currentpos' => [
'one'
]
};