将哈希数组插入另一个哈希数组中的元素中

时间:2014-12-23 20:12:16

标签: perl hash multidimensional-array 2d

我正在寻找一个如何实现哈希数组(带键和值)的解决方案,并将其插入(推送)到另一个哈希数组中,在一个未实例化的元素中;例如:

$variable1 = {

          0 => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          1 => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }
        };


$variable2 = { 'Biology' => 47, 'Theology' => 87 };

...

第一个variable1索引按时间顺序迭代为计数器0,1,2,3 ... n

因此,最终的变量1应该是......

$variable1 = {

          0 => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          1 => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }

          2 => {
                         'Biology' => 47, 
                         'Theology' => 87

                       } 


        };

2 个答案:

答案 0 :(得分:2)

为什么使用哈希作为外部结构?如果它是一个数组,那就是:

$variable1 = [
    {
        'Mathematics' => 82,
        'Art' => 99,
        'Literature' => 88
    },
    {
        'Mathematics' => 97,
        'Literature' => 67
    }
];

$variable2 = { 'Biology' => 47, 'Theology' => 87 };

push @$variable1, $variable2;

或者,如果您想推送副本(以便$variable1->[2]的更改不会影响$variable2),

push @$variable1, { %$variable2 };

根据您拥有的结构,您必须执行以下操作:

# assuming numbers are always sequential and start at 0
$variable1->{ keys %$variable1 } = $variable2;

# or if not
my $max_index = List::Util::max( keys %$variable1 ) // -1;
$variable1->{ $max_index+1 } = $variable2;

答案 1 :(得分:1)

由于您的密钥是数字的,并且您希望将新元素推入结构中,array of hashes更自然地保存您的数据,

use strict;
use warnings;
use Data::Dumper;

my @variable1 = (
  {
    'Mathematics' => 82,
    'Art' => 99,
    'Literature' => 88
  },
  {
    'Mathematics' => 97,
    'Literature' => 67
  }
);


my $variable2 = { 'Biology' => 47, 'Theology' => 87 };

push @variable1, $variable2;

print Dumper \@variable1;

输出

$VAR1 = [
      {
        'Art' => 99,
        'Literature' => 88,
        'Mathematics' => 82
      },
      {
        'Literature' => 67,
        'Mathematics' => 97
      },
      {
        'Biology' => 47,
        'Theology' => 87
      }
    ];