Perl How to access a hash that is the element of an array that is the value of another hash?
I am trying to create a Hash that has as its value an array.
The first element of the value(which is an array) is a scalar. The second elem开发者_StackOverflow中文版ent of the value(which is an array) is another hash.
I have put values in the key and value of this hash as follows :
${${$senseInformationHash{$sense}[1]}{$word}}++;
Here,
My main hash -> senseInformationHash
My Value -> Is an Array
So, ${$senseInformationHash{$sense}[1]}
gives me reference to my hash
and I put in key and value as follows :
${${$senseInformationHash{$sense}[1]}{$word}}++;
I am not sure if this is a correct way to do it. Since I am stuck and not sure how I can print this complex thing out. I want to print it out in order to check if I am doing it correctly.
Any help will be very much appreciated. Thanks in advance!
Just write
$sense_information_hash{$sense}[1]{$word}++;
and be done with it.
Perl gets jealous of CamelCase, you know, so you should use proper underscores. Otherwise it can spit and buck and generally misbehave.
A hash value is never an array, it is an array reference.
To see if you are doing it right, you can dump out the whole structure:
my %senseInformationHash;
my $sense = 'abc';
my $word = '123';
${${$senseInformationHash{$sense}[1]}{$word}}++;
use Data::Dumper;
print Dumper( \%senseInformationHash );
which gets you:
$VAR1 = {
'abc' => [
undef,
{
'123' => \1
}
]
};
Note the \1
: presumably you want the value to be 1, not a reference to the scalar 1. You are getting the latter because your ${ ... }++;
says treat what's in the curly braces as a scalar reference and increment the scalar referred to.
${$senseInformationHash{$sense}[1]}{$word}++;
does what you want, as does $senseInformationHash{$sense}[1]{$word}++
. You may find http://perlmonks.org/?node=References+quick+reference helpful in seeing why.
Thanks Axeman and TChrist.
The code I have to access it is as follows :
foreach my $outerKey (keys(%sense_information_hash))
{
print "\nKey => $outerKey\n";
print " Count(sense) => $sense_information_hash{$outerKey}[0]\n";
foreach(keys (%{$sense_information_hash{$outerKey}[1]}) )
{
print " Word wt sense => $_\n";
print " Count => $sense_information_hash{$outerKey}[1]{$_}\n";
}
}
This is working now. Thanks much!
精彩评论