sub read_table_to_hash { my ($dbh, %args) = @_; # example: # statement = "select col1, col2, col3 from table foobar" # keys = qw(col2) # # if return data is: # # col1_val1, col2_val1, col3_val1 # col1_val2, col2_val2, col3_val2 # col1_val3, col2_val3, col3_val3 # # hash will look like this: # { # fields => ['col1','col3'] # data => { # col2_val1 => ['col1_val1','col3_val1'], # col2_val2 => ['col1_val2','col3_val2'], # col2_val3 => ['col1_val3','col3_val3'], # } # } # my $statement= $args{statement}; my $params_aref = $args{params}; # key fields (will allow easy hash key # lookup) my $keys = $args{keys} or die "keys not defined!"; my $sth = $dbh->prepare($statement); my $fields = $sth->{NAME}; $sth->execute(@$params_aref) or die $sth->errstr; # fetch all records my %data_hash; my $key = uc(pop @$keys); # assume a single key only (for now) @{$data_hash{fields}} = grep(!/$key/, @$fields); while (my $row = $sth->fetchrow_hashref()) { # store in hash foreach my $field (@{$data_hash{fields}}) { push(@{$data_hash{data}{$row->{$key}}}, $row->{$field}); } } return \%data_hash; }