Listing 5: simple-find-2.pl
#!/usr/bin/perl -w
use strict;
use diagnostics;
use File::Find;
# Get the pattern from the input list
my $pattern = shift @ARGV;
# Slurp up the entire contents of a file
$/ = undef;
print qq{Searching for "$pattern".\n};
# Invoke "find" with a reference to our subroutine,
# with the directories passed as arguments
find(\&find_matches, @ARGV);
sub find_matches
{
my $filename = $_;
# Open the file, and search through its
# contents
if (open FILE, $filename)
{
# Get the file
my $contents = (<FILE>);
# If there aren't any contents, then return
# right away
return unless $contents;
# Print the filename, with the directory
print qq{$File::Find::dir/$filename\n}
if ($contents =~ m|\b$pattern\b|is);
close FILE;
}
else
{
warn qq{Unable to open
"$File::Find::dir/$filename": $! };
return;
}
}