formatting phones (was RE: Perl Script)

by David Mintz <mambomintz(at)yahoo.com>

 Date:  Wed, 28 Jun 2000 12:30:46 -0700 (PDT)
 To:  hwg-languages(at)hwg.org
  todo: View Thread, Original
I keep this little function in a library file to make
it conveniently re-usable. All you have to do is
'require' the library, then say 

$phone = format_phone($phone);

First it strips anything that isn't a digit from the
number. If what remains is 10 digits, we reformat,
otherwise send it back intact. (It could be greater
than 10 if it's an international number.)

Maybe later I'll make it smart enough to guess
intelligently if the person has included an extension.
Of course you could also make distinct text fields in
your form for the different components of the phone
number, as people sometimes do. I guess the question
is which way is Lazier.


sub format_phone {

    my $phone = shift;
    my $intact = $phone;
    $phone =~ s/^\s+(.*)\s+$/$1/;
    $phone  =~ tr/0-9//cd;

    if ( length($phone) == 10 ){

       $phone =~ s/(\d{3})(\d{3})(\d{4})/\($1\)
$2-$3/;
        return $phone;
   } else {
        return $intact
   }
}



David Mintz
Spanish Interpreter, US District Court
Southern District of New York
Web Design & Hosting http://www.dmintzweb.com
Personal http://www.panix.com/~dmintz

__________________________________________________
Do You Yahoo!?
Get Yahoo! Mail - Free email you can access from anywhere!
http://mail.yahoo.com/

HWG: hwg-languages mailing list archives, maintained by Webmasters @ IWA