Listing 7. simple-cgi-find.pl
#!/usr/bin/perl -w
use strict;
use diagnostics;
use File::Find;
use CGI;
use CGI::Carp qw|fatalsToBrowser|;
# Which directory should start the search?
my $search_root = "/usr/local/apache/htdocs";
# Slurp up files in one fell swoop
undef $/;
# Create an instance of CGI
my $query = new CGI;
# Send a MIME header
print $query->header("text/html");
# Get the text pattern for which to search
my $pattern = $query->param("pattern");
# Make sure that $pattern is defined
unless ($pattern)
{
    print $query->start_html(-title =>
       "No pattern named");
    print "<P>You must enter a pattern!</P>";
    print $query->end_html;
    exit;
}
# Start the HTML output
print $query->start_html(-title => "Search results");
print qq{<P>The following documents matched the
   pattern "$pattern":</P>\n};
# Start an unordered list
print "<ul>\n";
# Search for
find(\&find_matches, $search_root);
# End an unordered list
print "</ul>\n";
print $query->end_html;
#-----------------------------------------
# Subroutine that searches through files for
# matches
sub find_matches
{
    # Make sure that this is an HTML file
    return unless m/\.html?$/i;
    # Get the filename
    my $filename = $_;
    # Open the file, and search through its
    # contents
    if (open FILE, $filename)
    {
   # Get the file
   my $contents = (<FILE>);
   # Print the filename, with the directory
   print qq{<li>$File::Find::dir/$filename\n}
       if ($contents =~ m|\b$pattern\b|is);
   close FILE;
    }
    else
    {
   warn qq{Unable to open "$filename": $! };
   return;
    }
}