Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

City, State to/from Zip Code converter

by duelafn (Parson)
on Dec 13, 2001 at 21:03 UTC ( [id://131661]=CUFP: print w/replies, xml ) Need Help??

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

Replies are listed 'Best First'.
Re: City, State to/from Zip Code converter
by merlyn (Sage) on Dec 14, 2001 at 01:47 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://131661]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-19 11:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found