TedPride has asked for the wisdom of the Perl Monks concerning the following question:

I'm currently doing something like:
$counts{$n{'Rep'}}{$n{'Item'}} += $n{'Qty'};
This is fine if I always sort the data this way, but what if I decide I want to use a 3-level hash without hard-coding the data assignment? How do I efficiently take an array of keys:
@keys = ('Rep','Item','Whatever');
And translate it into:
$counts{$n{'Rep'}}{$n{'Item'}}{$n{'Whatever'}} += $n{'Qty'};
It doesn't have to be neat, or the fastest code on the planet, but efficiency is somewhat of a concern. I suppose I could use eval (since this is an admin script and placed safely out of reach of hackers), but I'm interested in seeing if there are other ways.

Replies are listed 'Best First'.
Re: Assigning data to a nested hash with a variable number of levels?
by tlm (Prior) on Apr 19, 2005 at 03:49 UTC

    This node (and its follow-ups) may be of interest. And this one.

    the lowliest monk

Re: Assigning data to a nested hash with a variable number of levels?
by TedPride (Priest) on Apr 19, 2005 at 04:36 UTC
    The module solution would probably work fine (assuming my client can figure out how to install the proper module), but the other post seems a bit confusing. It doesn't matter though - I finally figured out how to do it properly with references (or is it pointers?):
    use strict; use warnings; my %hash; assign(\%hash, 'aa', 'bb', 'cc', 'value'); print $hash{aa}{bb}{cc}; sub assign { my $p = shift; my $val = pop; my $last = pop; for (@_) { $p->{$_} = {} if !$p->{$_}; $p = $p->{$_}; } $p->{$last} = $val; }
    It came to me while I was lying in bed reading a book. Odd how that works.