Answers to Chapter 9 Exercises

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:

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

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*)/.

9.       Here's one way to do it:

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

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.

 



Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2001
Pages: 205

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net