Array in value of hash perl

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

Is it possible to assign the reference of an array as the value in the key : value pair of a hash table in perl?

回答1:

Yes it is. Create a reference to the array by using backslash:

$hash{key} = \@array; 

Note that this will link to the actual array, so if you perform a change such as:

$array[0] = "foo"; 

That will also mean that $hash{key}[0] is set to "foo".

If that is not what you want, you may copy the values by using an anonymous array reference [ ... ]:

$hash{key} = [ @array ]; 

Moreover, you don't have to go through the array in order to do this. You can simply assign directly:

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

Read more about making references in perldoc perlref



回答2:

Yes. See http://perlmonks.org/?node=References+quick+reference for some basic rules for accessing such data structures, but to create it, just do one of these:

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


回答3:

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"$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'                                                    }                           }             }; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!