Using Patterns to Match Digits

Yesterday I introduced you to the bare basics of pattern matching. You learned how to look for strings contained inside other strings, which gives you some flexibility in your scripts and what sort of input you can accept and test. Today, and in future days, you'll learn about new kinds of patterns you can use in the pattern operator /.../ and how to use those to make your scripts more flexible and more powerful.

Today we'll look at patterns that are used to match digits, any digit, from 0 to 9. Using what you learned yesterday you could test for digits like this:

if ($input =~ /1/ or $input =~ /2/ or $input =~ /3/ or $input =~ /4/ or
   $input =~ /5/ or $input =~ /6/ or ... }

But that would be a lot of repetitive typing, and Perl has a much better way of doing that same thing. The d pattern will match any single digit character, from 0 to 9. So, the statement $input =~ /d/ would test $input to see if it contained any numbers, and return true if it did. If input contained 1, it would return true. It would return true if input contained "23skidoo" or "luckynumber123" or "1234567".

Each d stands for a single digit. If you want to match two digits, you can use two d patterns:

$input =~ /dd/;

In this case "23skidoo" would return true, but "number1" would not. You need two digits in a row for the pattern to match.

You can also combine the d pattern with specific characters:

$input =~ /dupd/;

This pattern matches, in order: any digit, the character u, the character p, and then any digit again. So “3up4" would match; "comma1up1semicolon" would match; but "14upper13" would not. You need the exact sequence of any number and specific characters.

You can also match any character that is not a digit using the D pattern. D matches all the letters, all the punctuation, all the whitespace, anything in the ASCII character set that isn't 0 through 9. You might use this one specifically—as we will in the next section—to test your input to see if it contains any nonnumeric characters. When you want your input to be numeric, for example, if you were going to perform arithmetic on it, or compare it to something else numeric, you want to make sure there are no other characters floating around in there. D will do that:

$input =~ /D/;

This test will return true if $input contains anything nonnumeric. "foo" is true, as is "foo34", "23skidoo", or "a123". If the input is "3456" it will return false—there are only numeric characters there.

Table 3.3 shows the patterns you've learned so far.

Table 3.3. Patterns
Pattern Type What it does
/a/ Character Matches a
/d/ Any digit Matches a single digit
/D/ Any character not a digit Matches a single character other than a digit

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset