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

2019-02-25 15:57发布

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?

标签: arrays perl hash
1条回答
在下西门庆
2楼-- · 2019-02-25 16:06

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.

查看更多
登录 后发表回答