散列perl值的数组

时间:2012-12-20 04:12:19

标签: arrays perl hash reference

是否可以将数组的引用分配为perl中哈希表的key : value对中的值?

4 个答案:

答案 0 :(得分:23)

是的。使用反斜杠创建对数组的引用:

$hash{key} = \@array;

请注意,这将链接到实际数组,因此如果您执行更改,例如:

$array[0] = "foo";

这也意味着$hash{key}[0]设置为"foo"

如果这不是您想要的,您可以使用匿名数组引用[ ... ]复制值:

$hash{key} = [ @array ];

此外,您不必通过数组来执行此操作。您可以直接分配:

$hash{key} = [ qw(foo bar baz) ];

详细了解如何在perldoc perlref

中制作参考资料

答案 1 :(得分:10)

是。有关访问此类数据结构的一些基本规则,请参阅http://perlmonks.org/?node=References+quick+reference,但要创建它,只需执行以下操作之一:

%hash = ( 'somekey' => \@arrayvalue );
$hash{'somekey'} = \@arrayvalue;
%hash = ( 'somekey' => [ ... ] );

答案 2 :(得分:0)

use Data::Dumper; @name=('5/17',
    '5/17','5/17','5/17','5/17','5/17','5/17','5/17'); @status_flags=('U
    H L','U C','U H L','U C','U C','U H L','U C', 'U H L');
    @ip_address=('192.168.0.11','192.168.0.2','192.168.0.13','192.168.0.0','192.168.0.3','192.168.0.12','192.168.0.4','192.168.0.14'); @dp_id=('0','0','0','0','0','0','0','0');
    @ip_prefix_length=('32','32','32','24', '32', '32','32','32');

    for ($value=0;$value<=5;$value++) {


    $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'name'=>"$name[$value]"};
           $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'dp-id'=>"$dp_id[$value]"};
          $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'ip-address'=>"$ip_address[$value]"};
           $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'ip-prefix-length'=>"$ip_prefix_length[$value]"};


    $keyvals{'Response'}{'brocade-extension-ip-route'}{'extension-ip-route'}={'ip-gateway'=>'*'};




    }
        print Dumper \%keyvals;

    Each array value assign into hash value. $var1= {
              'Response' => {
                            'extension-ip-route' => {
                                                    'status-flags' =>  'U H L '
                                                                    ,
                                                    'ip-gateway' => '*',
                                                    'name' => '0/2',
                                                    'ip-address' =>  '192.168.20.11',
                                                    'dp-id' => '0',
                                                    'ip-prefix-length'=>'32'

                                                  }
                          }
            };

答案 3 :(得分:-1)

  %hash = ( 'somekey' => \@arrayvalue );
    $hash{'somekey'} = \@arrayvalue;

It is right. We can assign either hash or hash reference format.