noc_coder noc_coder - 4 months ago 6
Perl Question

Get a value from a reference to a hash

I know that there have been multiple posts about this topic already, but I have not found them to be helpful for my particular case.

When I run this excerpt of code

my $bandName = '';

my $rrh_sth = $dbh->prepare("SELECT serial....");
$rrh_sth->execute;

my $int_hash = $rrh_sth->fetchall_hashref('serial');
delete $_->{serial} for values %$int_hash;

foreach my $s ( keys %$int_hash ) {

if ( $values[6] eq $s ) {

#$bandName = @{%$int_hash}{$s};
$bandName = $int_hash ->{$s};

my $ulink = getFreq($bandName, "u");
my $dlink = getFreq($bandName, "d");

my $status = "active";

print Dumper (
$bandName,
$values[0],
$values[8],
$values[7],
$values[6],
$values[11],
$values[10],
$values[3],
$values[4],
$values[5],
$dlink,
$ulink
);
}
}


I keep getting the key and the value for the particular serial, represented by
$s
. I know that I have to de-reference
int_hash
, but I am not sure how now that the methods that I have tried do not work.

$VAR1 = {
'rrhName' => 'MCD59'
};
$VAR2 = 'MCO57';
$VAR3 = 'R-S-S:1-0-1';
$VAR4 = 'scb';
$VAR5 = '12NT46000050';
$VAR6 = undef;
$VAR7 = '109786038';
$VAR8 = 'MCO: 976 2x5W AC';
$VAR9 = 'enabled';
$VAR10 = '1';
$VAR11 = ''; #EDITED
$VAR12 = ''; #EDITED


In general, when I have a reference, I need to dereference it to get to the slices, but in the case of
$VAR1
, when I go to my database to see the value being inserted its telling me the position of
$VAR1
in memory, which is not what I thought I was asking for.

Answer

Your $int_hash is a hash reference, and you dereference it correctly into a hash, %$int_hash, to then retrieve its keys. The obtained key is then also used correctly to get the corresponding value, $int_hash->{$s}.

However, as the Dumper output shows, the value associated with the key $s is itself a hash reference. Since a reference itself is a scalar we can always assign it as a value to a key, which is how complex (nested) data structures are built. See perldsc for a cookbook, and for references in general perlreftut for a tutorial and perlref for a reference.

In short, you only need to keep dereferencing

$int_hash->{$s}->{'rrhName'};  # or,
$int_hash->{$s}{'rrhName'};    # or even
$int_hash->{$s}{rrhName};

The second and third lines are syntax shortcuts, explained in the above pages.

Either of these will return the value in the nested hash, MCD59.