Book HomeLearning Perl, 3rd EditionSearch this book

A.8. Answers to Chapter 9 Exercises

  1. Here's one way to do it:

    /($what){3}/

    Once $what has been interpolated, this gives a pattern resembling /(fred|barney){3}/. Without the parentheses, the pattern would be something like /fred|barney{3}/, which is the same as /fred|barneyyy/. So, the parentheses are required.

  2. Here's one way to do it:

    @ARGV = '/path/to/perlfunc.pod';  # or mentioned on the command line
    
    while (<>) {
      if (/^=item\s+([a-z_]\w*)/i) {
        print "$1\n";                 # print out that identifier name
      }
    }

    With what we've shown you so far, the only way to open an arbitrary file for input is to use the diamond operator (or to use input redirection, perhaps). So we put the path to perlfunc.pod into @ARGV.

    The heart of this program is the pattern, which looks for an identifier name on an =item line. The exercise description was ambiguous, in that it didn't say whether =item had to be in lower case; the author of this pattern seems to have decided that it should be a case-insensitive pattern. If you interpreted it otherwise, you could have used the pattern /^=item\s+([a-zA-Z_]\w*)/.

  3. Here's one way to do it:

    @ARGV = '/path/to/perlfunc.pod';  # or mentioned on the command line
    
    my %seen;                         # (optionally) declaring the hash
    
    while (<>) {
      if (/^=item\s+([a-z_]\w*)/i) {
        $seen{$1} += 1;               # a tally for each item
      }
    }
    
    foreach (sort keys %seen) {
      if ($seen{$_} > 2) {            # more than twice
        print "$_ was seen $seen{$_} times.\n";
      }
    }

    This one starts out much like the previous one, but declares the hash %seen (in case use strict might be in effect). This is called %seen because it tells us which identifier names we've seen so far in the program, and how many times. This is a common use of a hash. The first loop now counts each identifier name, as an entry in %seen, instead of printing it out.

    The second loop goes through the keys of %seen, which are the different identifier names we've seen. It sorts the list, which (although not specified in the exercise description) is a courtesy to the user, who might otherwise have to search for the desired item in a long list.

    Although it may not be obvious, this program is pretty close to a real-world problem that most of us are likely to see. Imagine that your webserver's 400-megabyte logfile has some information you need. There's no way you're going to read that file on your own; you'll want a program to match the information you need (with a pattern) and then print it out in some nice report format. Perl is good for putting together quick programs to do that sort of thing.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.