2015-06-04 19 views
0

使用Perl和DBI從SQL數據庫獲取數據。我正在使用下面的代碼從表中獲取數據。除了定義3個不同的數組之外,有沒有辦法用多個字段定義一個數組?Perl中的多字段數組

$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}; 
} 
+1

'的perldoc perldsc'陣列-的哈希值 – toolic

+0

請出示表模式和所期望的結果陣列的例子。 –

+0

tblPeople,fields Personid,currentpos,personnotes。不確定數組的結果,因爲我不知道Perl中有什麼。 –

回答

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' 
          ] 
     };