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

2019-02-25 16:08发布

问题:

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

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

Surprisingly, this reports (using Data::Dumper):

$VAR1 = {
      'a' => '1',
      '2' => undef
    };

This page gives an example of storing an array in a hash by defining the array use square brackets, like:

my $hash = {'a' => ['1', '2']};

That works, but I'm getting my array from a call to the split method. What's magic about square brackets versus parentheses for defining an array, and how can I turn a "parentheses-array" into a 'square-brackets' array?

回答1:

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.



标签: arrays perl hash