Search code examples
perlperl-data-structures

Hash Element of Array of arrays


I want "testhash" to be a hash, with an key of "hashelm", which contains an array or an array.

I do this:

$testhash{hashelm}=(
        ["1A","1B"],
        ["2A","2B"]
);

print Dumper(%testhash);

But I get this as output:

$VAR1 = 'hashelm';
$VAR2 = [
          '2A',
          '2B'
        ];

I would expect something more like:

$VAR1 = 
   hashlelm => (
        [
          '1A',
          '1B'
        ];
        [
          '2A',
          '2B'
        ];
   )

What am I missing?? I've been using perl for years and this one really has me stumped!!!


Solution

  • Hashes can only store scalar values; (["1A", "1B"], ["2A", "2B"]) is a list value. When evaluated in this scalar context, you only get the last item in the list, namely ["2A", "2B"]. You need to store a reference to a list value in the hash:

    $testhash{hashelm} = [ ["1A","1B"], ["2A","2B"] ];
    

    Read more in the perl documentation on list value constructors.