O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A.6. Chapter 7

  1. Here are some possible answers:

    1. /a+b*/

    2. /\\*\**/ (Remember that the backslash cancels the meaning of the special character following.)

    3. /($whatever){3}/ (You must have the parentheses, or else the multiplier applies only to the last character of $whatever; this also fails if $whatever has special characters.)

    4. /[\000-\377]{5}/ or /(.|\n){5}/ (You can't use dot alone here, because dot doesn't match newline.)

    5. /(^|\s)(\S+)(\s+\2)+(\s|$)/ (\S is nonwhitespace, and \2 is a reference to whatever the "word" is; the caret or whitespace alternative ensures that the \S+ begins at a whitespace boundary.)

    1. One way to do this is:

      while (<STDIN>) {
          if (/a/i && /e/i && /i/i && /o/i && /u/i) {
              print;
          }
      }

      Here, we have an expression consisting of five match operators. These operators are all looking at the contents of the $_ variable, which is where the control expression of the while loop is putting each line. The match operator expression will be true only when all five vowels are found.

      Note that as soon as any of the five vowels are not found, the remainder of the expression is skipped, because the && operator doesn't evaluate its right argument if the left argument is false.

    2. Another way to do this is:

      while (<STDIN>) {
          if (/a.*e.*i.*o.*u/i) {
              print;
          }
      }

      This answer turns out to be easier than the other part of this exercise. Here we have a simple regular expression that looks for the five vowels in sequence, separated by any number of characters.

    3. One way to do this is:

      while (<>) { print if ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required