![](/img/trans.png)
[英]Perl How to access a hash that is the element of an array that is the value of another hash?
[英]In Perl, how can I access a hash array element, that is itself another hash array?
我的代码中有一个哈希数组,该哈希数组是从Config :: General模块导入的,该模块包含多个级别的子哈希数组。 我正在尝试访问散列数组的子级中的变量,但它不断抱怨变量未定义。
如果我尝试将它们预先定义为哈希数组,则会抱怨内容未定义。 我显然在做一些愚蠢的事情,您能指出些什么吗?
my $key;
my $val;
# allDevices should be a hash array istelf
my $allDevices = $cfgfile{'remote_hosts'}{'category:switch'}{'subcategory:brocade'};
while (($key, $val) = each $allDevices)
{
# This proves that the $val is a hash array also
INFO(" - $key => $val\n");
# This bit works ok
my @devDetails = split(/:/, $key);
my $thisDevice = $val;
my $thisDeviceType = $devDetails[0];
my $thisDeviceName = $devDetails[1];
INFO(" - Device Name: $thisDeviceName\n");
# This is where it complains - %thisDevice requires explicit package name
my $thisDeviceConnectProto = $thisDevice{'remote_device_connect_protocol'};
my $thisDeviceConnectIP = $thisDevice{'remote_device_connect_ipaddress'};
my $thisDeviceConnectUser = $thisDevice{'remote_device_connect_username'};
my $thisDeviceConnectPass = $thisDevice{'remote_device_connect_password'};
#########################################################################
# For each command specified in cli file #
#########################################################################
# CLI "for" loop
}
提前致谢
不要忘记在代码中use strict
use warnings
。 它们在编译阶段对您有很大帮助。 例如:
# file: test.pl
use strict;
use warnings;
my $hash = {'one'=>1}; #hash reference
print $hash{'one'}, "\n"; #error: this refers to %hash, and it doesn't exists
print $hash->{'one'}, "\n"; #ok
perl解释器显示以下错误消息:
Global symbol "%hash" requires explicit package name at test.pl line 7
您没有声明%thisDevice
哈希,而$thisDevice
hashref完全是另一个变量。
更改
$thisDevice{'remote_device_connect_protocol'};
至
$thisDevice->{'remote_device_connect_protocol'};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.