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]
$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.
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.