Perl - How to store and access an array in a hash of hashes?
I am in need of some syntax help. I'm trying to figure out how to store and retrieve an array out of a hash of hashes. For this example, I'm trying to access the city list for a particular state for a particular country. I understand I could do a join and split on the hash key to combine Country and State, but trying to keep things separated.
The code I have gets in all the information for the Countries, and states, and gets the list of cities together, no problem. I store all the city names in an array, then make an anonymous pointer to the array for the hash, like this - $MY_CITIES{$COUNTRY}{$STATE} = [@CITIES] I believe that syntax is correct, or is it? What I'd like to do is I need to cycle through every hash to find if a city exists or not. If it exists in 3 states, then it should print 3 times. Here is the code block to search - Code:
for $COUNTRY (@LIST_OF_COUNTRIES) { 1.) Is my assignment of $MY_CITIES{$COUNTRY}{$STATE} = [@CITIES] right to assign the cities to that hash of hashes key? 2.) My second loop line with for $STATE, how to I walk all the State keys within the $MY_CITIES{$COUNTRY}{$STATE} hash? keys %MY_CITIES{$COUNTRY}{$STATE} like that? 3.) The if statement that does the search for the city in the anonymous stored array, is that written correctly? ${$MY_CITIES}{$COUNTRY}{$STATE}? Thanks for the help! Devon |
Quote:
Code:
1 PERL(1) Perl Programmers Reference Guide PERL |
And a quick tip: Instead of dereferencing a lot with ${${$[ etc, use the "dereferencing-member-access-operator" ->
like $foo->{'bar'}->[42] (here $foo is a hash ref and the element 'bar' in the hash is an array ref) much better readable... |
I got it finally. The HoH section in man perldsc got me on the right track, and some fine guessing on my part finally gelled it.
The whole ${${$ thing, in some examples I agree with, and in others, I find it easier with the ${${$ etc way. Multi-layer deep, absolutely. At the third dimension, it's not very difficult, and reads more cleanly with the ${$ methodology, to me. Devon |
Quote:
1. Yes, correct. 2. No. It should be keys %{ $MY_CITIES{$COUNTRY} } 3. No. It should be $MY_CITIES{$COUNTRY}{$STATE}[$INDEX] Also, the Index line has an error as well. It should be $#{$MY_CITIES{$COUNTRY}{$STATE}} Devon |
All times are GMT -5. The time now is 10:09 PM. |