Search code examples
perlhashhash-of-hashes

Creating hash of hash dynamically in perl


I am trying to create a hash of hash of - the nesting depth depends on the number of arguments passed into @aGroupByFields array.

In the below implementation, I am getting the desired hash structure.But I have hard coded the fields [ example - $phBugRecord->{createdBy} ] instead of deriving it from the array.

I am not sure how to dynamically create this.

my (@aGroupByFields) = ['createdBy','status','devPriority']; 
# In real case,these are passed in as arguments

my (%hTemp); 
# This is the final hash which will be structured according to above fields

# %hBugDetails is the hash containing details of all bugs

foreach my $phBugRecord ( @{ $hBugDetails{records} } ) {

    # The below statement needs to be generated dynamically as 
    # opposed to the hard-coded values.
    push(
        @{
            $hTemp{ $phBugRecord->{createdBy} }{ $phBugRecord->{status} }
                { $phBugRecord->{devPriority} }
        },
        $phBugRecord
    );

}

Any pointer will be a great help.Thanks.


Solution

  • This code will do what you need

    my @aGroupByFields = qw/ createdBy status devPriority /;
    
    my %hTemp;
    
    for my $phBugRecord ( @{ $hBugDetails{records} } ) {
    
        my $hash = \%hTemp;
    
        for my $field ( @aGroupByFields ) {
    
            my $key = $phBugRecord->{$field};
    
            if ( $field eq $aGroupByFields[-1] ) {
                push @{ $hash->{ $key } }, $phBugRecord;
            }
            else {
                $hash = $hash->{ $key } //= {};
            }
        }
    }