Blob


1 #!/usr/bin/perl
3 # Make a program that reads a list of strings from a file, one
4 # string per line, and then lets the user interactively enter
5 # patterns that may match some of the strings. For each pattern,
6 # the program should tell how many strings from the file matched,
7 # then which ones those were. Don't reread the file for each new
8 # pattern; keep the strings in memory. The filename may be
9 # hardcoded in the file. If a pattern is invalid (for example, if
10 # it has unmatched parentheses), the program should simply report
11 # that error and let the user continue trying patterns. When the
12 # user enters a blank line instead of a pattern, the program should
13 # quit. (If you need a file full of interesting strings to try
14 # matching, try the file sample_text in the files you've surely
15 # downloaded by now from the O'Reilly website; see Chapter 1.)
17 use v5.24;
18 use warnings;
19 use strict;
20 use utf8;
22 if (scalar(@ARGV) != 1) {
23 die "Usage: $0 file\n";
24 }
26 my $file = shift @ARGV;
28 open my $fh, '<', $file or die "Unable to open '$file': $!";
29 chomp(my @lines = <$fh>);
30 my $pattern;
32 print "Pattern (blank to quit): ";
33 while (chomp($pattern = <>) && $pattern !~ /\A\s*\z/) {
34 my @matches = eval {
35 grep /$pattern/, @lines;
36 };
37 if ($@) {
38 print "'$pattern' is not a valid regular expression!\n";
39 } else {
40 printf("%s: %s has %d matches\n", $file, $pattern, scalar(@matches));
41 print join("\n",@matches);
42 print "\n";
43 }
44 print "Pattern: ";
45 }
47 # When the user enters a blank line instead of a pattern, the
48 # program should quit. (If you need a file full of interesting
49 # strings to try matching, try the file sample_text in the files
50 # you've surely downloaded by now from the O'Reilly website; see
51 # Chapter 1.)