tags:

views:

121

answers:

4

I think what I need is an Array of Array of Hash, but I have no idea how to make that.

Can Perl do that?

And if so, how would the code look like?

+5  A: 

You can address elements of such a data structure thus:

$x->[1][2]{foo} = "hello"

You don't even have to pre-define the structure. Just start working with the elements as if they're already there.

Marcelo Cantos
This feature of Perl is known as **autovivification**.
Alan Haggai Alavi
Does it work nicely with `use warnings` and `use strict`?
Dummy00001
@Dummy000001: yes.
Marcelo Cantos
Please don't use the variable `$a` (or `$b`) in examples that don't involve `sort`. `$a` and `$b` are special variables in Perl and can cause odd errors when used outside of a function passed to `sort`.
Ven'Tatsu
+4  A: 
my $aah =
        [ # outer array
                [ # first inner array
                        { # first inner hash
                                foo => 'bar',
                        },
                        { # second inner hash
                                bar => 'baaz',
                        },
                ],
                [ # secnd inner array
                        #...
                ],
                # ...
        ];

You can access the elements like this:

$aah->[0]->[1]->{bar} # => 'baaz'
jkramer
Or `$aah->[0][1]{bar}`... everything in an array or hash is a scalar, thus any substructures can be assumed to be references, thus only the first arrow is ever needed.
Axeman
Or `$$arr[0][1]{bar}`. I personally prefer that over the `->` notation.
Dummy00001
This doesn't need to be an array reference, replace the first [ with ( the last ] with ) and $aah with @aah. Now you can access the data like this: $aah[0][1]{bar}; no de-referencing syntax needed, for the reason stated by Axeman.
MkV
A: 
my $arr = 
  [
    [
      {key1 => $value1, key2 => $value2},
      {key1 => $value3}
    ],
    [
      {rubbish => 'nonsense'},
    ]
   ];

etc.

Colin Fine
Just because its a nested data structure doesn't mean it needs to be an arrayref, it can be an array of arrayrefs of hashrefs.
MkV
@MkV: Most programmers would prefer the arrayref, since it's cheaper and simpler to pass around as a data structure than a list would be. BTW, did you downvote this answer? If so, that's a pretty lame reason to do so.
Marcelo Cantos
Of course it can be an array rather than an arrayref at the top. So what? It doesn't change the answer in any significant way. I don't know why you felt it necessary to add that comment to my and jkramer's answers.
Colin Fine
+6  A: 

perldoc perldsc is a good document to read to get an idea of data structures in Perl.

Alan Haggai Alavi