On Tue, Jun 12, 2001 at 08:23:43PM -0000, Big Bird wrote:
> I have a hash of zipcode-city pairs. Since a city may have more than one
> zip code, the zipcodes are the keys. If there is exactly 1 value in the
> hash that matches the city in the line of the file, I need to get the key
> for that value, but how can I do it?
As far as I understand the description, you want the zipcode for a city if,
and only if, the city only has one zipcode.
One solution is to reverse the hash then delete any city entries with
multiple zip codes.
Assuming your zipcode-to-city data structure looks like this:
%zipcode2city = (
99999 => ["Metropolis", "Gotham City"],
99998 => ["Dark City"],
...
);
Where all values are anonymous arrays, then one way to reverse it is like
so:
my %city2zipcode;
while (my($zip, $cities) = each(%zipcode2city)) {
foreach my $city (@$cities) {
push(@{ $city2zipcode{$city} }, $zip);
}
}
Then filter:
foreach my $city (keys %city2zipcode) {
if (@{ $city2zipcode{$city} } > 1) {
delete $city2zipcode{$city};
} else {
$city2zipcode{$city} = $city2zipcode{$city}[0];
}
}
Now, you have but to look in %city2zipcode for your 1-zipcode cities.
One other method is to combine the reverse and filtering by using a seperate
data structure to track which cities have multiple zipcodes as you go.
Michael
--
Administrator www.shoebox.net
Programmer, System Administrator www.gallanttech.com
--