Unable to store array as a hash value

后端 未结 2 1088
孤城傲影
孤城傲影 2021-01-27 03:29

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

相关标签:
2条回答
  • 2021-01-27 03:54

    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.

    0 讨论(0)
  • 2021-01-27 04:08
    $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.

    0 讨论(0)
提交回复
热议问题