从数组创建一个散列的多维密钥? [英] Create a multidimesional key of hash from array?

查看:128
本文介绍了从数组创建一个散列的多维密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 @array 创建一个多维%hash



假设 @array 就像

 我的@阵列=(1,2,3,4,5); 

我想分配 @array 上一个值作为多维%散列的最终值,即

 %hash =(
1 => {
2 =>
{
3 =>
{
4 => 5
}





$ b $这意味着 $ hash {1} {2} {3} {4} = 5;



我想这样做:对于我的$ i(0 .. $#数组),

 {
#push $ i作为关键字,直到倒数第二个元素和将最后一个元素赋值为
}

注意: @array 可以是任何大小,只是我想给 @array 中最后一个元素之前的元素键指定最后一个元素 c $ c>%hash

解决方案

首先,使用 pop 分隔要从键分配的值。然后,您可以使用以下任一项:

 使用Data :: Diver qw(DiveVal); 

my%hash;
DiveVal(\%hash,map \ $ _,@keys)= $ val;

  sub dive_val:lvalue {
my $ p = \shift;
$ p = \($$ p-> {$ _})for @_;
$$ p
}

my%hash;
dive_val(\%hash,@keys)= $ val;

dive_val 通过 $ p 引用下一个取消引用和/或修改的值。

 预回路: $ p引用$ hash(引用%散列的匿名标量)
循环传递之后0:$ p引用$ hash-> {1}
循环传递1之后:$ p引用$ hash-> {1} {2}
循环传递2之后:$ p引用$ hash-> {1} {2} {3}
循环传递3之后:$ p引用$ hash-> { 1} {2} {3} {4}

额外的间接级别有很多好处。 / b>


  • 它不需要专门处理最后一个键。
  • 它不需要创建在解除引用之前进行散列。
  • 它不需要将根作为对散列的引用。相反,任何标量都可以是根,甚至可以是未定义的。

  • 它可以很容易地扩展 dive_val 来支持混合数组/散列结构。


I want to create a multidimensional %hash from the @array.

Suppose @array is like

my @array=(1,2,3,4,5);

I want to assign @array last value as final value to multidimensional %hash i.e

%hash=(
        1=>{ 
              2=>
                 {
                  3=>
                      {
                        4=>5
                       }
                  }
              }
           )

Which means $hash{1}{2}{3}{4}=5;

I want to do it in something like:

for my $i (0..$#array){
    #push $i as key until second last element and assign last element as value
} 

Note : The @array may be of any size, Just I want to assign last element of @array as value to the keys of elements before the last element in %hash.

解决方案

First, use pop to separate the value to assign from the keys. Then, you can use either of the following:

use Data::Diver qw( DiveVal );

my %hash;
DiveVal(\%hash, map \$_, @keys) = $val;

or

sub dive_val :lvalue {
   my $p = \shift;
   $p = \( $$p->{$_} ) for @_;
   $$p
}

my %hash;
dive_val(\%hash, @keys) = $val;

dive_val works by having $p reference the next value to dereference and/or modify.

Pre-loop:            $p references $hash (the anon scalar referencing %hash)
After loop pass 0:   $p references $hash->{1}
After loop pass 1:   $p references $hash->{1}{2}
After loop pass 2:   $p references $hash->{1}{2}{3}
After loop pass 3:   $p references $hash->{1}{2}{3}{4}

The extra level of indirection has many benefits.

  • It removes the need to treat the last key specially.
  • It removes the need to create the hash before it's dereferenced.
  • It removes the need for the root to be a reference to a hash. Instead, any scalar can be the root, even an undefined one.
  • It makes it easy to extend dive_val to support mixed array/hash structures.

这篇关于从数组创建一个散列的多维密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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