Tanalis has asked for the wisdom of the Perl Monks concerning the following question:
I'm writing a fairly nasty piece of code atm which will read in a table from a database (using Sybase::DBlib) and hash it based on user-provided keys (it has to be done this way - I need to read a lot of tables and need the reusability).
I am storing each row's data as it comes from the DB in a temporary hash keyed on column name, and want to append this to the master hash keyed on the specified columns (there could currently be up to 5 keys).
My problem comes when appending the data to the master hash - because the number of keys is unknown, I can think of no "clean" way to append the data. I have experimented a little with recursion, to no avail, and am left currently with long and ugly code which copes with up to 3 keys - which isn't enough. Is there an "easier" way to place this data into the hash?
Any suggestions would be appreciated.
My code atm is as follows:
# download the data from the db, using a trapped alarm in case of db # failure (prevents an infinite wait). alarm 600; local $SIG{ALRM} = sub { return $FALSE; }; $dbh -> dbcmd("SELECT * FROM $table"); $dbh -> dbsqlexec; $dbh -> dbresults; # get the column names for the data my @columnames; for (my $i = 0; $i <= $dbh -> dbnumcols; $i++) { push (@columnames, $dbh -> dbcolname($i)); } # write the table data to a hash my %tableData; while (my @data = $dbh -> dbnextrow) { my %tblData; for (my $i = 0; $i < $#columnames; $i++) { $data[$i] =~ s/^\s|\s$//g; $tblData{$columnames[$i+1]} = $data[$i]; } # get the data keys and hash accordingly my $hashkey = $tblData{$key}; delete $tblData{$key}; if (defined $key3) { # if there are 3 keys my $hashkey2 = $tblData{$key2}; my $hashkey3 = $tblData{$key3}; delete $tblData{$key2}; delete $tblData{$key3}; %{$tableData{$hashkey}{$hashkey2}{$hashkey3}} = %tblDa +ta; } elsif (defined $key2) { # if there are 2 keys my $hashkey2 = $tblData{$key2}; delete $tblData{$key2}; %{$tableData{$hashkey}{$hashkey2}} = %tblData; } else { # there's only 1 key %{$tableData{$hashkey}} = %tblData; } } return \%tableData;
I'm sure there must be a better way to do this, but I really can't see it.
Thanks -- Foxcub.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Recursive hash assignment
by davorg (Chancellor) on Sep 05, 2002 at 09:35 UTC | |
|
Sample Data Structure
by Tanalis (Curate) on Sep 05, 2002 at 09:20 UTC | |
by Tanalis (Curate) on Sep 05, 2002 at 09:53 UTC | |
|
Re: Recursive hash assignment
by seeken (Novice) on Sep 06, 2002 at 05:13 UTC | |
|
Partial solution - but it's very slow
by Tanalis (Curate) on Sep 06, 2002 at 11:49 UTC | |
|
Re: Recursive hash assignment
by Aristotle (Chancellor) on Sep 06, 2002 at 15:07 UTC | |
|
Re: Recursive hash assignment
by blssu (Pilgrim) on Sep 06, 2002 at 20:53 UTC | |
|
Re: Recursive hash assignment
by Anonymous Monk on Sep 07, 2002 at 00:37 UTC |