Validating phone number using perl

我的梦境 提交于 2021-02-10 20:18:10

问题


I want to validate phone number with following conditions:

  1. length should be 10 digits
  2. should start with 7 or 8 or 9

If it does not meet these requirements, we should fail the number.

I have tried the following:

print "Enter phone number: \n";
$name=<>;
chomp $name;

if (length($name)==10 && $name==~  m{/[^7-9]/}){
  print "$name is valid \n";
}
else {
  print "$name is not valid \n";
}

回答1:


I would just use a single regex here:

^[789][0-9]{9}$

This avoids having to spread your validation logic across a few places.

if ($name =~ m{/^[789][0-9]{9}$/}){
    print "$name is valid \n";
}
else {
    print "$name is not valid \n";
}



回答2:


It might be worth explaining what was wrong with your original version. You have two checks. The first one (length($name)==10) is fine. The problems are with the second one.

$name==~  m{/[^7-9]/}

There are three problems here. Firstly, you're using the wrong operator. You know you need to bind your variable ($name) to your match operator, but the binding operator is =~ not ==~. But, unfortunately, your operator isn't wrong enough to throw a syntax error. Perl will interpret it as a numeric comparison (==) followed by a bitwise negation (~). That's certainly not what you want!

Your second problem is with the match operator. It looks like you know that the match operator is m/.../ and that you also know you can choose an alternative delimiter for the match operator - you've picked m{...}. But you shouldn't nest those delimiters. When you use m{/.../} you're are looking for two literal characters / in your string.

Finally, there's a problem with your actual regex. You want the string to start with 7, 8 or 9. Putting those digits in a character class ([7-9]) is a good idea. But you shouldn't also place the start of string anchor (^) inside the character class. At the start of a character class, ^ has a different meaning - it means "not one of the characters listed here". So your character class ends up meaning the exact opposite of what you wanted it to mean.

Your match expression should have looked like this:

$name =~ m{^[7-9]}

Making your complete code:

print "Enter phone number: \n";
$name = <>;
chomp $name;

if (length($name) == 10 and $name =~  m{^[7-9]}) {
  print "$name is valid \n";
}
else {
  print "$name is not valid \n";
}

(I did a little tidying - adding some whitespace around operators and switching && for and as is has lower precedence. You might also consider revising your variable name. $name is not a great name for a variable that contains a phone number!)



来源:https://stackoverflow.com/questions/54862088/validating-phone-number-using-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!