Home > Articles > Web Development > Perl

  • Print
  • + Share This
This chapter is from the book


  1. I want to iterate over a string and count the occurrences of the letter t. How can I do this in Perl?

  2. Well, you could use a for loop and one of the string functions to work your way through the string one character at a time, but that would be a terrible amount of overkill (and expose you as a C programmer who still thinks of strings as null-terminated arrays). Perl's good with strings, and it has built-in mechanisms for finding stuff in strings so you don't have to do perverse character-by-character comparisons. You'll learn more about this sort of pattern matching on. Don't spend a lot of time iterating over strings until you read that.

    I don't understand why in these scripts you are testing for nonnumeric data using \D, when we could be testing for numeric data using \d. To me it would make more sense to just test for numbers if you want numbers.

    The problem is that both \d and \D stand for just one character. So you could test for numeric data with \d and your pattern would match perfectly as long as your input was 1, 2, 3, 4, and so on, through 9. But if your input was 10 or above, that would be more than a single character, and would not match the pattern, and, therefore, produce an error. Theoretically you want your test to work for any number: 1 should be just as acceptable as 11 or 111111. Later on you'll learn how to do a pattern that matches one or more digits. For now, matching a single nondigit character is an easy work around, the data itself can be any number of characters but all you need is one character to be the wrong thing.

  3. Can I use printf just like I do in C?

  4. Well, you can, but you should really get used to working with print instead. The print function is more efficient, and helps cover up things like rounding-off errors in floating-point numbers. It's really a much better idea to use print for the vast majority of cases and only fall back on printf for specific reasons (like rounding).

    If you do use printf, you can use all the formatting codes you can in the C version of printf except for *.

  5. Why is it important that some functions are functions and some functions are actually operators? Don't they all behave the same?

  6. Nope. Functions and operators behave slightly different. Functions, for example, have a higher precedence. And arguments to an operator might be grouped based on precedence (giving you odd results) as well. In most cases, however, the difference between a function and an operator should not cause you to lie awake at night.

  • + Share This
  • 🔖 Save To Your Account