noc_coder noc_coder - 4 months ago 4
Perl Question

Get the hash value from a reference to a hash PERL

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 dereference 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 de-reference 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.

Thanks for the help!

Answer

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

However, as the Dumper output shows, the value itself is a hash reference, so you only need to keep dereferencing

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

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

Comments