Mike's Web

Lesson 6: Simple Searching

This lesson covers searching for data in a single file. If you're looking for something to search your entire site, that's beyond the scope of this course, and I don't recommend you try and write one yourself - there are a number of fine site-indexing tools already available, such as Glimpse or SWISH. I use SWISH to index the Steve Jackson Games website and like it a lot.

At any rate, on to searching. There are several ways to search for data. If you're searching a single file, you can either loop through each record one at a time and try matching for the data you're looking for, or you can use perl's grep() function to search all the data at once. Which of these you use depends on your program.

Say you have a product database, like this one (from our last lesson):

Suppose you want to let someone search the database for a book title, or part of a title. You'd have a simple form, something like:

Then, your cgi will read the entire data file and use Perl's grep function to search for the data. The actual syntax for grep is:
The /pattern/ is a regular expression for the pattern you're matching on.

Here's an example:

This example will work. Unfortunately it will also match things in other fields, as well - for example, if your visitor enters a number (try entering "12"), they could get back a book matching that stock number, or even that price. To check against that, you could modify the above script by testing the results lines against the field you want people to search on. Here's an example (just swap out this code for the results loop in your previous script):

And here's the form using the above example:

In this example, I've kept another flag outside the loop ($found), and set it to 1 only if the search string really matched the name of a book. If it didn't, that means something else was matched, but I don't want the user to know that, so I just print the "No results found".

One final way to search a file would be to not use grep at all, but instead simply loop through each element in the file and try matching for the data you are looking for. Replace the results loop in the first script with this code:

And here's the form using the above example:

There's nothing wrong with this approach unless your data is very large. Perl can easily zip through a small file of a few hundred records pretty quickly, but if you have a database with 20,000 names in it, this approach might take a little longer. (And if you have that much data, anyway, a better solution would be to use a sql database engine, rather than flat files.)


Copyright © 1997 by Jacqueline D. Hamilton All Rights Reserved.


Mike's Home | Lesson 1 | Lesson 2 | Lesson 3 | Lesson 4 | Lesson 5 | Lesson 6 | Generic Lesson