28 October 2014

Quiz 41: Find whether a phone number is valid or not

Problem:
Given a phone number, find whether number is valid or not.
Rule1: number should have 10 digits
Rule2: only numbers allowed


Input Format: 
n = no. of test cases
followed by n numbers in different lines

Output Format: 
print corresponding error for each line. print "Valid number" for valid number

Constraints: 
none

Sample Input
3
9876543210
999999999
9876543w21

Sample Output:
valid phone number
Phone number should have length 10
Phone number should have numbers only

Explanations:
for case 2, length is 9, so number is invalid


Solution:

chomp($n=<STDIN>);
for($i=0;$i<$n;$i++)
{
chomp($s=<STDIN>);
@arr=split(//,$s);
$l=@arr;
$c=0;
if($l != 10)
{
push(@out,"Phone number should have length 10");
$c++;
}
foreach(@arr){
if($_ !~ /\d/)
{
push(@out,"Phone number should have numbers only");
$c++;
last;
}}
if($c == 0)
{
push(@out,"valid phone number");
}
}
foreach(@out)
{
print "$_\n";
}


Tips:
\d is used to match digits only. [0-9] can also be used.

No comments:

Post a Comment