johnlowvale johnlowvale - 1 month ago 17
Perl Question

Perl: How to access an array in a hash

I have a sample hash with an array inside, but it seems wrong the way I access the elements of the array. I do it this way:

%Hash_Object = (
"Property1","value-1",
"Property2",("value-2","value-3")
);

print $Hash_Object{Property2}[1];
#blank output!


It is supposed to print out "value-3", but it doesn't.

Answer

Always use use warnings; and use strict in top of the program.

If you use this it display the following errors

Odd number of elements in hash assignment at array.pl line 3.
Can't use string ("value-2") as an ARRAY ref while "strict refs" in use at array.pl line 8

In perl, where list are flatten together.

so the first error is

Odd number of elements in hash assignment at array.pl line 3

Hashes must has pairs of keys and value. So the elements of the hash should not be an odd number.

Your code should be

use warnings;
use strict;
my %Hash_Object = (
  "Property1"=>["value-1"],
  "Property2"=>["value-2","value-3"]
);

print $Hash_Object{Property2}[1];
Comments