< Day Day Up > |
Exercise: The Unix grepAs you get further along in this book, the exercises will present you with more and more useful tools. This exercise presents a stripped-down version of the Unix grep utility. The Unix grep ”not to be confused with Perl's grep function, introduced in Hour 6, "Pattern Matching" ”searches files for patterns. This exercise presents a utility that will prompt for a directory name and a pattern. Every file in that directory will be searched for that pattern, and lines matching that pattern will be printed. In future exercises, this utility will be modified to search subdirectories (see Hour 15, "Finding Permanence") and to take command-line arguments (see Hour 12, "Using Perl's Command-Line Tools"). Stay tuned for details. Using your text editor, type the program from Listing 10.1 and save it as mygrep . If possible, be sure to make the program executable according to the instructions you learned in Hour 1, "Getting Started with Perl." Also, make sure that you don't rename this file to grep on a Unix system because it could be mistaken for the real grep utility. When you're all done, try running the program by typing the following at a command line: perl -w mygrep or, if your system enables you to make the file executable, mygrep Listing 10.1. Complete Listing for mygrep1: #!/usr/bin/perl -w 2: 3: use strict; 4: 5: print "Directory to search: "; 6: my $dir=<STDIN>; chomp $dir; 7: print "Pattern to look for: "; 8: my $pat=<STDIN>; chomp $pat; 9: 10: my($file); 11: 12: opendir(DH, $dir) die "Cannot open $dir: $!"; 13: while ($file=readdir DH) { 14: next if (-d "$dir/$file"); 15: if (! open(F, "$dir/$file") ) { 16: warn "Cannot search $file: $!"; 17: next; 18: } 19: while(<F>) { 20: if (/$pat/) { 21: print "$file: $_"; 22: } 23: } 24: close(F); 25: } 26: closedir(DH);
Listing 10.2 shows a sample of the mygrep program's output. Listing 10.2. Output from mygrepDirectory to search: /home/clintp Pattern to look for: printer mailbox: lot of luck re-inking Epson printer ribbons with config.pl: # the following allows the user to pick a printer for |
< Day Day Up > |