Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

cwest (1514)

cwest
  (email not shown publicly)
http://caseywest.com/
AOL IM: caseyrwest (Add Buddy, Send Message)

Perl geek.

Journal of cwest (1514)

Saturday January 25, 2003
12:31 AM

US Postal State Codes

[ #10183 ]

So, I thought it would be fun to have a regex that checks for a valid State Postal Code. There are 57 codes for the US, so I wanted to write a program to produce the regex. Here's the program:


#!/usr/local/bin/perl
use strict;
use warnings;

my @states = qw[
    AL AK AS AZ CA CO CT DE DC FM
    FL GA GU HI ID IL IN IA KS KY
    LA ME MH MD MA MN MS MO MT NE
    NV NH NJ NM NY NC ND MP OH OK
    OR PW PA PR RI SC SD TN TX UT
    VT VI VA WA WV WI WY
];

my %sets = ();
my @sets = ();

foreach ( @states ) {
    my ($first, $last) = split //;
    push @{$sets{$first}}, $last
              unless exists $sets{$last} && grep { $first eq $_ } @{$sets{$last}};
}

foreach ( keys %sets ) {
    push @sets, sprintf '%s[%s]', $_, join( '', @{$sets{$_}} );
}

my $regex = join '|', map "\n\t$_", @sets;

print "qr/(${regex}\n)/x\n";

And the output:


qr/(
                A[LKSZ]|
                C[AOT]|
                D[EC]|
                F[ML]|
                G[AU]|
                H[I]|
                I[DLNA]|
                K[SY]|
                M[EHDANSOTP]|
                N[EVHJYCD]|
                O[HKR]|
                P[WAR]|
                R[I]|
                S[CD]|
                T[NX]|
                U[T]|
                V[TIA]|
                W[AVIY]
)/x

Of course this is a nearly unmaintainable piece of junk, but it was really fun to build.

The Greatest Story Ever Told - "All The Hype That Money Can Bu" by Five Iron Frenzy

Posted from caseywest.com, comment here.