在perl哈希引用中添加另一个键是行不通的

时间:2016-05-27 05:53:23

标签: perl-data-structures

提前致谢,您的回答非常有用。

我从数据库中使用arrayofhashref获取两个$sth->fetchall_arrayref({})让我们a和b在哪里

a= [
          {
            'name' => 'test',
            'id' => '10',`enter code here`
          },
          {
            'name' => 'foo',
            'id' => '22',
          }
   ];

b= [
      {
            'dept' => 'IT',
            'mob' => '880978'
          },
          {
            'dept' => 'CSE',
            'mob' => '877687'
          },
       ];

The o/p should be :


a= [
          {
            'name' => 'test',
            'id' => '10',
             b= [
                   {
                     'dept' => 'IT',
                     'mob' => '880978'
                   },
                  {
                    'dept' => 'CSE',
                    'mob' => '877687'
                 },
              ];
          },
          {
            'name' => 'foo',
            'id' => '22',
             b= [
                  {
                   'dept' => 'IT',
                   'mob' => '880978'
                 },
                {
                   'dept' => 'CSE',
                   'mob' => '877687'
                 },
              ];

          }
   ];

I did like :
my $count = 0;
foreach my $row (@$a){
     $a->[$count]{b} = $b;
    $count++;
}

如果我将$ b作为“heloo”传递它工作正常,但我怎么能传递这个散列引用数组?

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解了您的问题,但您的代码似乎正在运作。

#!/usr/bin/env perl

use strict;
use warnings;

use Test::More tests => 1;

my $a = [
    {
        'name' => 'test',
        'id' => '10',
    },
    {
        'name' => 'foo',
        'id' => '22',
    }
];

my $b = [
    {
        'dept' => 'IT',
        'mob' => '880978'
    },
    {
        'dept' => 'CSE',
        'mob' => '877687'
    },
];

#The o/p should be :

my $wanted = [
    {
        'name' => 'test',
        'id'   => '10',
        b      => [
            {
                'dept' => 'IT',
                'mob' => '880978'
            },
            {
                'dept' => 'CSE',
                'mob' => '877687'
            },
        ],
    },
    {
        'name' => 'foo',
        'id'   => '22',
        b      => [
            {
                'dept' => 'IT',
                'mob' => '880978'
            },
            {
                'dept' => 'CSE',
                'mob' => '877687'
            },
        ],
    }
];

#I did like :

my $count = 0;
for my $row (@$a){
    $a->[$count]{'b'} = $b;
    $count++;
}

is_deeply($a, $wanted, 'data structures equal');

给出:

1..1
ok 1 - data structures equal