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