user3691037
user3691037

Reputation: 7

In Perl, how can I access a hash array element, that is itself another hash array?

I've got an hash array in my code, imported from the Config::General module that contains multiple levels of child hash arrays. I'm trying to access the variables within the hash array's child, yet it continually complains about variables being undefined.

If I try to define them as hash arrays in advance it complains that the contents are undefined. I'm clearly doing something stupid, are you able to point out what?

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
}

Thanks in advance

Upvotes: 0

Views: 78

Answers (2)

Miguel Prz
Miguel Prz

Reputation: 13792

Don't forget to use strict and use warnings in your code. They helps you a lot in the compiling phase. For example:

# 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

The perl interpreter shows this error message:

Global symbol "%hash" requires explicit package name at test.pl line 7  

Upvotes: 3

mpapec
mpapec

Reputation: 50637

You didn't declare %thisDevice hash and $thisDevice hashref is completely another variable.

Change

$thisDevice{'remote_device_connect_protocol'};

to

$thisDevice->{'remote_device_connect_protocol'};

Upvotes: 2

Related Questions