如何存储阵列作为一个Perl的哈希值? [英] How do I store an array as a value in a Perl hash?

查看:319
本文介绍了如何存储阵列作为一个Perl的哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建在Perl中,它的值是数组的哈希。是这样的:

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?

推荐答案

哈希值(和数组)元素是标量,所以你不能存储阵列的一个哈希值。

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

以下都是等价的:

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] 同样的方式创建一个数组,受让人列表来,然后返回数组的引用。

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

这篇关于如何存储阵列作为一个Perl的哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆