Uses the zip code finder at
www.usps.gov to match a zip code to a city, or a city to a zip code. It's simple and short, but I learned about
LWP::UserAgent and how exactly \G works in a regexp.
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
my $USPS = 'http://www.usps.com/cgi-bin/zip4/ctystzip2';
my $FormDataID = 'ctystzip';
my ($x, @matches);
if (@ARGV) { $x = join " ", @ARGV; }
else { print 'Enter Search (zip code OR city, state): ';
chomp( $x = <STDIN> ); }
# Prepare data to send to the USPS
my $ua = new LWP::UserAgent;
my $req = new HTTP::Request POST => $USPS;
$req->content_type('application/x-www-form-urlencoded');
$req->content($FormDataID.'='.$x); # HTTP::Request handles URL encodin
+g.
# Request the page, and ignore initial content
my $res = $ua->request($req);
my $data = $res->content;
$data =~ /----------</g;
# If a zip code was submitted, we are looking for CITY STATE
if ($x =~ /^\s*\d{5}\s*/) {
while ($data =~ /\G.*?br>\s*((\w+\s)+\s*\w\w) /ig) {
push @matches, $1; }
@matches = map { $_ = reverse $_;
/^\s*(\w\w)\s*(\w.*)$/;
scalar reverse "$1 ,$2"; }
@matches;
}
# Otherwise, Extract the zip codes.
else {
while ($data =~ /\G.*?br>\s*(\d{5})/ig) {
push @matches, $1; }
for (@matches) { s/^\s+//; s/\s+$//; }
}
print 'Found ',$#matches+1," matches for $x\n ",
join("\n ", @matches),"\n";
__END__
=head1 NAME
zipcode.pl - City, State to/from Zip Code converter
=head1 SYNOPSIS
perl zipcode.pl [City, State]
or
perl zipcode.pl [Zip Code]
=head1 AUTHOR
Dean Serenevy <dean@serenevy.net>
=cut