How do I store an array as a value in a Perl hash?

前端 未结 1 1178
不知归路
不知归路 2021-01-22 19:43

I\'m trying to create a hash in Perl, whose values are arrays. Something like:

my @array = split(/;/, \'1;2\');
my $hash = {\'a\' => @array};
<
相关标签:
1条回答
  • 2021-01-22 20:30

    The values of hash (and array) elements are scalars, so you can't store an array into a hash.

    The following are all equivalent:

    my $hash = { a => @array };
    my $hash = { 'a', @array };
    my $hash = { 'a', $array[0], $array[1] };
    my $hash = { a => $array[0], $array[1] => () };
    

    A common solution is to store a reference to the array.

    my @array = split(/;/, '1;2');
    my $hash = { a => \@array };   # my $hash = { a => [ '1', '2' ] };
    

    [ LIST ] similarly create an array, assigns LIST to it, then returns a reference to the array.

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