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

7.7. Exercises

See Appendix A for answers.

  1. Construct a regular expression that matches:

    1. at least one a followed by any number of b's

    2. any number of backslashes followed by any number of asterisks (any number might be zero)

    3. three consecutive copies of whatever is contained in $whatever

    4. any five characters, including newline

    5. the same word written two or more times in a row (with possibly varying intervening whitespace), where "word" is defined as a nonempty sequence of nonwhitespace characters

    1. Write a program that accepts a list of words on STDIN and looks for a line containing all five vowels (a, e, i, o, and u). Run this program on /usr/dict/words [9] and see what shows up. In other words, enter:

      $ myprogram </usr/dict/words
      (This presumes you name your program myprogram.)

      [9] Your system's dictionary may be somewhere other than /usr/dict/words ; check the spell (1) manpage.

    2. Modify the program so that the five vowels have to be in order and intervening letters don't matter.

    3. Modify the program so that all vowels must be in an increasing order, so all five vowels have to be present, and no "e" can occur before an "a", no "i" can occur before an "e", and so on.

  2. Write a program that looks through /etc/passwd [10] (on STDIN), printing the login name and real name of each user. (Hint: use split to break the line up into fields, then s/// to get rid of the parts of the comment field that are after the first comma.)

    [10] If using NIS, your system may have little data in /etc/passwd. See if ypcat ...

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