I coded up a solution first and then used the other answers to check my code. (This is a fun site. I wish I had more time.) This is very similar to davorg's solution, but a little more finished. The bonus to his solution is he tested it... ;)

The original used alternation in the regex, which some (all?) versions of perl don't optimize. The original also used column name $i+1 for column value $i. That looked a lot like a bug since it wasn't documented, so I changed it too.

# query setup omitted. # @keys is an array of your primary keys. The # first element of the array is the key used in # %tableData. Each following key is used to # identify a nested hash. my $last_key = pop @keys; my %tableData; while (my @data = $dbh -> dbnextrow) { my $row = { }; my $i = 0; foreach my $value (@data) { $value =~ s/^\s+//; $value =~ s/\s+$//; $row->{$columnames[$i++]} = $value; } my $nest = \%tableData; my $key_value; foreach my $key_name (@keys) { $key_value = delete $row->{$key_name}; $nest = ($nest->{$key_value}) ? ($nest->{$key_value}) : ($nest->{$key_value} = { }); } $key_value = delete $row->{$last_key}; $nest->{$key_value} = $row; } return \%tableData;

In reply to Re: Recursive hash assignment by blssu
in thread Recursive hash assignment by Tanalis

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.