Having some trouble understanding how to create a Perl hash from a DB select statement.
$sth=$dbh->prepare(qq{select authorid,titleid,title,pubyear from books});
$sth->execute() or die DBI->errstr;
while(@records=$sth->fetchrow_array()) {
%Books = (%Books,AuthorID=> $records[0]);
%Books = (%Books,TitleID=> $records[1]);
%Books = (%Books,Title=> $records[2]);
%Books = (%Books,PubYear=> $records[3]);
print qq{$records[0]\n}
print qq{\t$records[1]\n};
print qq{\t$records[2]\n};
print qq{\t$records[3]\n};
}
$sth->finish();
while(($key,$value) = each(%Books)) {
print qq{$key --> $value\n};
}
The print statements work in the first while loop, but I only get the last result in the second key,value loop.
What am I doing wrong here. I'm sure it's something simple. Many thanks.
$Books{AuthorID} = $records[0];(etc). Here can use a "slice" as well:@Books{qw(AuthorID TitleID Title PubYear)} = @recors;. But with this it's hopefully clear that the next row of values overwrites the previous, etc, and only the last row remains. (Unless you do have only one row in the table?) Another option for accumulating results is an array of hashes -- an array which has hash-references like above. So choose your data structure :)