Brad
Brad

Reputation: 11515

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!!!

Upvotes: 0

Views: 99

Answers (2)

chepner
chepner

Reputation: 531155

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.

Upvotes: 6

dgw
dgw

Reputation: 13646

This will work:

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

You have to use the square brackets for an anonymous array.

Upvotes: 5

Related Questions