If the files are not all that big (to justify using a database, as I would do if the files were big, and then run an SQL Query), or I wanted a little practice honing up my hashes of hashes skills I might do the following (I have removed some code to let you work out some details, this is probably not the optimal way but it is one way):
My logic goes as follows:
1. open <FILE2> and place all the cities in a hash keyed by zipcode something like:
chomp($line) #line from FILE2 my ($zip_code,$city) = split /\|/,$line; $zip_city{$zip_code} = $city; #insert city into hash
2. open <FILE1> again split it and compare the keys in my original hash setting the state and city in a hash again keyed against zip (the delete $zip_city{$current_zipcode}; part is so that I don't continue to go over zips I already have a state for, you could also put a last; so it would not continue reading from <FILE1> once the hash %zip_city contained no keys).
3. Lastly for each line in <FILE3> I would see if the zipcode (assuming you put it in a variable called $zipfrom3)existed in the second hash (%zip_city_state hash) and if it does print the info you want:chomp($line); my ($state,$min,$max) = split /,/,$line; foreach my $current_zipcode ( keys %zip_city ) { if ( $current_zipcode >= $min and $current_zipcode <= $max ) { $zip_city_state{$current_zipcode}{city} = $zip_city{$current_zipc +ode}; $zip_city_state{$current_zipcode}{state} = $state; delete $zip_city{$current_zipcode}; } }
or else complain that it did not exist in the hash (if you use warnings; it will do a good job of complaining if you don't check for the existance of a zip in the hash first, but you should check for the existance anyhow).print "$zipfrom3,$zipzip_city_state{$zipfrom3}{city}, $zip_city_state{ +$zipfrom3}{state}\n";
-enlil
In reply to Re: How to match zip code to city,state
by Enlil
in thread How to match zip code to city,state
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |