Section A.15. Answer to Chapter 16 Exercise

A.15. Answer to Chapter 16 Exercise

  1. Here's one way to do it:

         my $filename = 'path/to/sample_text';     open FILE, $filename       or die "Can't open '$filename': $!";     chomp(my @strings = <FILE>);     while (1) {       print "Please enter a pattern: ";       chomp(my $pattern = <STDIN>);       last if $pattern =~ /^\s*$/;       my @matches = eval {         grep /$pattern/, @strings;       };       if ($@) {         print "Error: $@";       } else {         my $count = @matches;         print "There were $count matching strings:\n",           map "$_\n", @matches;       }       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. 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: 2003
Pages: 232

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: