Just a little recursive hash-of-hashes function builder I wrote for a system I work on.

A hash reference is the first argument, followed by an array reference of hash-keys, followed by and optional hash of key-value pairs to put on the tail end of the hash.

The reason for the hashref as the first parameter is so that you can continue to call the routine in a loop or some other such nonesense and add to the existing hash without trashing it.

Perhaps we can get a golf game going on this one, too... Reduced whitespace/comments don't count. :)

EDIT:

Props to jynx for noticing an innefficiency for me to fix in this edit.

EDIT2:

More props to George_Sherston for noticing some left-over code from the original implimentation. %fieldTypes was used to place values into the final hash if the field was a summarization, hence the lookup on the $key name.

sub hash_maker { my $ref = shift; my $key = shift; return undef unless ref $ref eq 'HASH'; # # If $key is empty, we're building an empty hash. Return undef. # return undef unless $key; # # This is the passed in hash, so we need to duplicate it in our new # data structure. We also have to be sure that we're adding if neces +sary. # if ( ref $key eq 'HASH' ) { foreach my $k ( keys %{$key} ) { $ref->{$k} = $key->{$k}; } return $ref; } # # Reference was not a hashref, we don't know how to handle it. # return undef if ref $key; # # Nothing above was met, there's more to build. # $ref->{$key} = {} unless exists $ref->{$key}; hash_maker( $ref->{$key}, @_ ); # # Pass that which we hath groweth to those who groweth before us... # return $ref; }

In reply to Recursive Hash Maker by Bobcat

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.