Sandra Schlichting
Sandra Schlichting

Reputation: 25986

Array of Hashes in Hash of Hashes?

I have this HoH

#!/usr/bin/perl

use warnings;
use strict;

my $a = {
    '0' => {
            'i' => -1,
            'u'  => -1,
    },
};

But what I would like is

my $a = {
    '0' => {
            'i' => -1,
        'u'  => -1,
            (
              {
               'i' => -1,
               't' => -1,
              },
            ),
          },
        };

which gives an error.

Is it not possible in have an AoH in a HoH?

Upvotes: 0

Views: 847

Answers (2)

BadFileMagic
BadFileMagic

Reputation: 701

It's probably yelling you "Odd number of elements in anonymous hash at $filename line $line", right? That's because you can't really just stuff an array into a hash by itself -- the array ref will need to be keyed, just like any other hash element. Also, you will need to use [] instead of () to make an array ref:

my $a = {
    0 => {
        i => -1,
        u => -1,
        x => [{i => -1, t => -1}],
    },
};

produces no errors. Then you can access into it like so: $a->{0}{x}[0]{i};

Upvotes: 8

Toto
Toto

Reputation: 91373

You should have a key before your array :

my $a = {
    '0' => {
            'i' => -1,
            'u'  => -1,
            'a' => [
      # here ^ is the key
              {
               'i' => -1,
               't' => -1,
              },
            ],
          },
        };

Upvotes: 2

Related Questions