CGI and Perl

Introduction

This example shows you how to provide a search engine into your own Web site. The front end is a simple form with a text field, a Submit button, and a Reset button. The back end recurses through your Web site's directories, scanning the HTML files for the existence of the specified string. The resulting page will contain either a message that no items have been found, or it will display a list of navigable links to those pages that match the search criteria.

Defining the Search Scope

The form for this example is a simple one. Using CGI::Form, Listing 7.8 contains the code.

Defining the Search Scope

The form for this example is a simple one. Using CGI::Form, Listing 7.8 contains the code.

Listing 7.8. Subroutine to return a search form.

sub searchForm {
    my($q)=@_;
    print $q->header;
    print $q->start_html("Search My Site");
    print "<H1>Search My Site</H1>\n<HR>\n";
    print "<P>Please enter one or more words to search for";
    print " and click `Search'<BR>\n";
    print $q->start_multipart_form();
    print $q->textfield(-name=>`SearchString',-maxlength=>100,-size=>40);
    print "<BR><BR><BR>";
    print $q->submit(-name=>`Action',-value=>`Search');
    print " ";
    print $q->reset();
    print $q->endform();
    print $q->end_html();
 }

This form appears in your browser as shown in Figure 7.5.


Figure 7.5. The search form as it appears in your browser.


When the user clicks Search, the real work begins. In this example, you will search the entire site, but depending on the size of your site, you might want to limit the search scope by adding another field to your form. This can be accomplished by using a pull-down menu or a group of radio buttons.