Answer to Chapter 17 Exercise

A.16 Answer to Chapter 17 Exercises

1.       Here's one way to do it:

2.          my $filename = 'path/to/sample_text';
3.          open FILE, $filename
4.           or die "Can't open '$filename': $!";
5.          chomp(my @strings = <FILE>);
6.          while (1) {
7.           print "Please enter a pattern: ";
8.          chomp(my $pattern = <STDIN>);
9.           last if $pattern =~ /^\s*$/;
10.      my @matches = eval {
11.      grep /$pattern/, @strings;
12.      };
13.      if ($@) {
14.      print "Error: $@";
15.      } else {
16.      my $count = @matches;
17.      print "There were $count matching strings:\n",
18.     map "$_\n", @matches;
19.      }
20.      print "\n";
}

This one uses an eval block to trap any failure that might occur when using the regular expression. Inside that block, a grep pulls the matching strings from the list of strings.

Once the eval is finished, we can report either the error message or the matching strings. Note that we "unchomped" the strings for output by using map to add a newline to each string .

 



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