Using regular expressions, write a complete Perl script that, when given the inp
ID: 3842652 • Letter: U
Question
Using regular expressions, write a complete Perl script that, when given the input from a sample as shown below, displays ONLY the valid phone numbers found anywhere in the file. For this example assume a phone number is valid only if it is in the following form (where 9 represents anynumber):
(999)-999-9999
Sample Input:
this is a test
12345676867
(123)-456-7890
My number: (123)-555-1212
test 9999 test.
A phone number ((123)-999-0000) exists on this line.
There is no phone number ((123)-999+0000) on this line.
Sample Output:
(123)-456-7890
(123)-555-1212
(123)-999-0000
this is a test
12345676867
(123)-456-7890
My number: (123)-555-1212
test 9999 test.
A phone number ((123)-999-0000) exists on this line.
There is no phone number ((123)-999+0000) on this line.
Explanation / Answer
Answer:
open(INPUT, "<$input_file") or die "cannot open file";
open(OUTPUT, ">$display_file") or die "cannot open file";
while ($value = <INPUT>)
{
$value =~ s/ + //;
($read_value, $xxxxxx, $xxxxxx) = split(";", $value);
($prefix_value, $postfix_value) = split("-", $read_value);
$prefix_size = length ($prefix_value);
$postfix_size = length ($postfix_value);
if ($prefix_size < 2 || $postfix_size < 5 )
{
print "Invalid phone number: $read_value ";
}
else
{
print "Valid phone number: $read_value ";
}
}
close INPUT;
close OUTPUT;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.