0

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

0

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow - after all this time - never really groked the difference between a list and an array. The part about the hash storing only a scalar value makes a lot of sense, though. Thanks!
5

This will work:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.