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



gerble1000
User

Jul 18, 2012, 3:53 AM


Views: 1420
if string is numeric and 11 digits long

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


Views: 1417
Re: [gerble1000] if string is numeric and 11 digits long

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


Views: 1413
Re: [BillKSmith] if string is numeric and 11 digits long

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


Views: 1408
Re: [gerble1000] if string is numeric and 11 digits long

\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


Views: 1399
Re: [BillKSmith] if string is numeric and 11 digits long

ideal thankyou bill