How To Split a Phone Number [PERL]


Phone numbers, as we know, are most commonly made of three elements (area code) prefix-number. If your program or a script has to process phone numbers some times it is useful to separate the three elements and store them in separate variables. Below I will show you how you can achieve this in Perl using the build-in substr function.

The substr function will extract a string of characters, with predefined length and starting at specific position, from a scalar string passed to it. First argument we provide is the data string; the second is the starting character number (starting the count at zero); the third is the length of the substring you would like returned.

# Split a 10 digits phone number.

my $userPhone = '7085869028';

# Declare the variables and their values.
my $splitPhoneAreaCode = substr($userPhone, 0, 3);
my $splitPhonePrefix = substr($userPhone, 3, 3);
my $splitPhoneNumber = substr($userPhone, -4);

# Print the variables values on the screen.
print $splitPhoneAreaCode . "\n\n";
print $splitPhonePrefix . "\n\n";
print $splitPhoneNumber . "\n\n";

If we provide only two arguments, the data string and a negative number, e.g. $splitPhoneNumber in the above example, the character count will start from the end of the data string and the length of the string returned will be the number we provided.

Here is another example – phone number only, without the area code.

# Phone number, without the area code.

my $userPhone = '7085869026';

# Declare the variable and its values.
my $phoneLast7 = substr($userPhone, -7);

# Print the variable's value on the screen.
print "$phoneLast7\n\n";

Read more about using substr at the Perldocs. There you can see some really nice examples ofsubstr syntax.


Discover more from Titan Fusion

Subscribe now to keep reading and get access to the full archive.

Continue reading