Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Answer to Chapter 17 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. Note that we “unchomped” the strings for output by using map to add a newline to each string.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page