CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
if string is numeric and 11 digits long

 



gerble1000
User

Jul 18, 2012, 3:53 AM

Post #1 of 5 (882 views)
if string is numeric and 11 digits long Can't Post

could sombody help me with this please.
i need to check if $string is all numeric and if 11 digits long and starts with 07 else do other

examples would be
07232343576
07569898665
0946nd769
gciasu8neeeo

i need a simple if else statement


BillKSmith
Veteran

Jul 18, 2012, 4:33 AM

Post #2 of 5 (879 views)
Re: [gerble1000] if string is numeric and 11 digits long [In reply to] Can't Post

If you are sure that $string contains what you think, use a regular expression. But be warned, if perl changes the numeric string to a number, the leading 0 is lost.


Code
   

use strict;
use warnings;
my @strings = (
'07232343576',
'07569898665',
'0946nd769',
'gciasu8neeeo',
);
foreach my $string (@strings) {
if ($string =~ /07\d{9}/) {
print "valid: $string\n";
}
else {
print "invalid $string\n";
}
}

Good Luck,
Bill


gerble1000
User

Jul 18, 2012, 5:48 AM

Post #3 of 5 (875 views)
Re: [BillKSmith] if string is numeric and 11 digits long [In reply to] Can't Post

that worked great thanyou, could you explain why it works.
just need a breakdown like y is there a 9 and what does the 'd' do


BillKSmith
Veteran

Jul 18, 2012, 6:22 AM

Post #4 of 5 (870 views)
Re: [gerble1000] if string is numeric and 11 digits long [In reply to] Can't Post

\d is a 'character class' which means match any decimal digit.

{9} is a 'quantifier' which means use 9 of the previous item (any digit). The 9 comes from eleven digits minus the two (07) already matched.

I forgot the anchors. The RE that I posted would match the specified pattern anywhere within a longer string. It should be:


Code
  

if ($string =~ /^07\d{9}$/) {

Good Luck,
Bill


gerble1000
User

Jul 18, 2012, 8:11 AM

Post #5 of 5 (861 views)
Re: [BillKSmith] if string is numeric and 11 digits long [In reply to] Can't Post

ideal thankyou bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives