7cc9a587a136196a52132b3d4a729151ddaf7c74
[migration-tools.git] / compile_zips
1 #!/usr/bin/perl -w
2 use strict;
3
4 # Given input like "Miami Springs\tFL\t33166\n" derived from patron addresses,
5 # this utility will print a city and state for each zip that has the maximum
6 # number of occurrences. (It does not attempt to break ties. If there is a tie,
7 # the city and state that reaches the maximum first will end up winning.)
8
9 my %zips;
10
11 # Go through the input and tally the city-state combinations for each ZIP code
12 while (<>) {
13         chomp;
14         (my $city, my $state, my $zip) = split(/\t/) or next;
15         next unless $zip =~ m/([\d]{5})/; # If it doesn't have 5 digits in a row, it's not a ZIP
16         $zip =~ s/^([\d]{5}).*$/$1/;      # We only want the 5-digit ZIP
17         $state = uc($state);
18         $zips{$zip}{"$city\t$state"}++;
19 }
20
21 # Pick and print a winner for each ZIP code
22 foreach(sort keys %zips) {
23         my $zip = $_;
24         my $max = 0;
25         my $citystate = "";
26         foreach(keys %{$zips{$zip}}) {
27                 if ($zips{$zip}{$_} > $max) {
28                         $max = $zips{$zip}{$_};
29                         $citystate = $_;
30                 }
31         }
32         print "$citystate\t$zip\n";
33 }