Unable to store array as a hash value

2019-03-01 03:45发布

问题:

I'm trying to store an array (not array ref) in a hash but it is treating the array in scalar context and only storing the last value of array in the $hash->{key}.

use Data::Dumper;
$h->{'a'} = ( 'str_1', 'str_2' );
print Dumper $h;

Output: $VAR1 = { 'a' => 'str_2' };

Why can't I store an array in hash-Key and access the array elements as $hash->{key}[index]

回答1:

$h->{'a'} = [ 'str_1', 'str_2' ];

You can only store scalar as a hash value, and scalar can be simple value or array reference.

Check perldoc.



回答2:

Values of a hash have to be scalar values, cannot be arrays or hashes. So you need to use array reference as the value of $h->{'a'}:

$h->{'a'} = [ 'str_1', 'str_2' ];

and access them by using

$h->{'a'}->[0]; # for 'str_1'
$h->{'a'}->[1]; # for 'str_2'

By the way, as pointed out by @RobEarl, you also can use the following syntax

$h->{'a'}[0]; # for 'str_1'
$h->{'a'}[1]; # for 'str_2'

See perlref for how to create and use different kind of references.



标签: arrays perl hash