Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2 Dimensional Hash 1

Status
Not open for further replies.

Kiehlster

MIS
Joined
Aug 14, 2000
Messages
147
Location
US
Is it possible to make a 2 dimensional hash table? I'm trying to make a program that hashes words by their alphabet letter, then I want to have it hash each of the words of each alphabet letter by a number like this:

%WordsStartingWithA = $Alphabet{'a'};
$FirstWord = $WordsStartingWithA{'1'};

will this work? or do I have to just make 26 hash tables?
Steve Kiehl
webmaster@nanovox.com
 
Yes, you can has a 2 dimensional hash (also known as a hash of hashes). But I think you really want a hash of arrays.

For example:
%HoW = (
a => [ "all", "animal", "an" ],
b => [ "ball", "baby", "bottle" ],
c => [ "candle", "cane"],
);
print "Words starting with 'a': @{ $HoW{a} } \n";
print "First word starting with 'a': $HoW{a}[0] \n";
 
In my case, each word comes with a pronunciation, a topic, the part of speech, and a definition, so I need something that has each access to the words and an easy way of sorting them.
Steve Kiehl
webmaster@nanovox.com
 
Why didn't you say so in the first place :)

You definitely want a hash of hashes. Here's an example:

%HoW = (
a => {
all => {
pron => "xxx",
topic => "yyy",
def => "zzz",
},
animal => {
pron => "aaa",
topic => "bbb",
def => "ccc",
},
},
b => {
ball => {
pron => "eee",
topic => "fff",
def => "ggg",
},
bell => {
pron => "hhh",
topic => "iii",
def => "jjj",
},
},
);

sub alpha { $a cmp $b; }
foreach $letter ( sort alpha keys (%HoW) ) {
print "Letter $letter \n";
foreach $word ( sort alpha keys %{ $HoW{$letter} } ) {
print "$word $HoW{$letter}{$word}{pron} $HoW{$letter}{$word}{topic} $HoW{$letter}{$word}{def} \n";
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top