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; }

Replies are listed 'Best First'.
Re: Recursive Hash Maker
by jynx (Priest) on Nov 14, 2001 at 06:17 UTC

    i'm confused,
    What's the purpose of %hash?

    jynx

      Uhm... It's just there so somebody would ask me why. :)

      Upon further examination, it's not needed and was overlooked when I went through the function and optomized it a little bit.

      Score one for jynx.