在perl中动态创建哈希散列 [英] Creating hash of hash dynamically in perl

查看:253
本文介绍了在perl中动态创建哈希散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建散列哈希值 - 嵌套深度取决于传入 @aGroupByFields 数组中的参数数量。



在下面的实现中,我得到了所需的散列结构。但是我已经硬编码了这些字段[示例 - $ phBugRecord-> {createdBy} ]而不是从数组派生它。



我不确定如何动态创建它。

  my(@aGroupByFields)= ['createdBy','status','devPriority']; 
#在实际情况下,这些以参数传递

my(%hTemp);
#这是根据上述字段结构化的最后一个散列

#%hBugDetails是包含所有错误细节的散列

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

#下面的语句需要动态生成,与硬编码值相反的
#。
push(
@ {
$ hTemp {$ phBugRecord-> {createdBy}} {$ phBugRecord-> {status}}
{$ phBugRecord-> {devPriority }}
},
$ phBugRecord
);




$ b $ p
$ b

任何指针都会有很大帮助。谢谢。 p>

解决方案

这段代码会做你所需要的事情

  my @aGroupByFields = qw / createdBy status devPriority /; 

my%hTemp;

为我的$ phBugRecord(@ {$ hBugDetails {records}}){

my $ hash = \%hTemp;

for my $(@aGroupByFields){

my $ key = $ phBugRecord-> {$ field};

if($ field eq $ aGroupByFields [-1]){
push @ {$ hash-> {$ key}},$ phBugRecord;
}
else {
$ hash = $ hash-> {$ key} // = {};
}
}
}


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.

解决方案

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 } //= {};
        }
    }
}

这篇关于在perl中动态创建哈希散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆