If you want to convert a US phone number into the format xxx-xxx-xxxx, then you can use this nice simple function.
sub convert_tel {
my $tel = $_[0];
if ($tel =~ /^\d+$/) {
$tel =~ s/([\d]{3,3})/$1-/g;
$tel =~ s/\-$//g;
return $tel;
} else {
return $tel;
}
}
That would convert a 10 digit number into 123-123-123-1. However, it would be nicer to have it formatted as xxx-xxx-xxxx, so to get that lets do this regex instead:
$tel =~ s/([\d]{3,3})([\d]{3,3})([\d]{3,4})/$1-$2-$3/g;
Simply call with:
print convert_tel("123412341234");
Thats about it =)
Categories: Perl Coding