Just for fun of it lets assume that we deal with North American number which consists of 11 digits
- pos1: 1 - North America
- pos2: 2-4 - Area code
- pos3: 5-7 - Group1
- pos4: 8-11 - Group2
The code snippet: validation is implemented on verification that number consists of 11 digits only
use strict;
use warnings;
use feature 'say';
my %number; # has to store number
while(my $data = <DATA>) { # walk through data
chomp $data; # snip eol
$data =~ tr/0-9//cd; # remove spaces, brakets, dashes
if( length($data) != 11 ) { # is number consist of 11 digits?
say '-' x 40 . "\n" # no = invalid
. "Number: $data is invalid";
} else { # yes = valid
$data =~ /(\d)(\d{3})(\d{3})(\d{4})/; # regex and capture
@number{qw/country area group1 group2/} = ($1,$2,$3,$4); # store
say '-' x 40 . "\n"
. "Belongs to "
. ($number{country} == 1 ? "North America" : "None North America");
say "Number: $data\n" # output
. "Record: $number{country} ($number{area}) $number{group1}-$number{group2}\n"
. "Country: $number{country}\n"
. "Area: $number{area}\n"
. "Group1: $number{group1}\n"
. "Group2: $number{group2}";
}
}
__DATA__
1 (309) 123-4567
1 312-123-4567
1 (815) 123-456
3 (421) 123-4567
3 (426) 123-4567
17731234567
1872123456
Output
----------------------------------------
Belongs to North America
Number: 13091234567
Record: 1 (309) 123-4567
Country: 1
Area: 309
Group1: 123
Group2: 4567
----------------------------------------
Belongs to North America
Number: 13121234567
Record: 1 (312) 123-4567
Country: 1
Area: 312
Group1: 123
Group2: 4567
----------------------------------------
Number: 1815123456 is invalid
----------------------------------------
Belongs to None North America
Number: 34211234567
Record: 3 (421) 123-4567
Country: 3
Area: 421
Group1: 123
Group2: 4567
----------------------------------------
Belongs to None North America
Number: 34261234567
Record: 3 (426) 123-4567
Country: 3
Area: 426
Group1: 123
Group2: 4567
----------------------------------------
Belongs to North America
Number: 17731234567
Record: 1 (773) 123-4567
Country: 1
Area: 773
Group1: 123
Group2: 4567
----------------------------------------
Number: 1872123456 is invalid