Listing 4: dbsearch.pl, a simple search program which retrieves
results from the MLDBM file created by index-files.pl

#!/usr/bin/perl -w

use strict;
use diagnostics;
use File::Find;
use HTML::Entities;
use Fcntl;
use MLDBM qw(DB_File);
use CGI;
use CGI::Carp qw(fatalsToBrowser);

# Create an instance of CGI
my $query = new CGI;

# Send a MIME header to the user's browser
print $query->header("text/html");

# In what file should the index be stored?
my $index_file = "/tmp/lj.db";

# Create the word index hash, and tie it to the file
my %data;
tie %data, "MLDBM", $index_file, O_RDONLY
    or die "Error tying %data: $! ";

# Get the user's search term
my $term = lc $query->param("term");

# Make sure that the term contains non-whitespace
unless ($term =~ /\S/)
{
    print $query->start_html(-title => "No search term!");
    print "<P>Please enter a search term.</P>\n";
    print $query->end_html;
    exit;
}

# Get the hash for this word
my $results = $data{$term};

# Results
my %results = %$results if (defined $results);

# Give a warning if there were no results
unless (%results)
{
    print $query->start_html(-title => "No matches!");
    print qq|<P>Sorry, but there were no matches to "$term".</P>\n|;
    print $query->end_html;
    exit;
}

print $query->start_html(-title => "Search results");
print "<P>There were ", scalar keys %results, " results to your query:</P>\n";

print "<ul>\n";

# If there were results, sort them by frequency
foreach my $url (sort {$results{$a} <=> $results{$b} } keys %results)
{
    print qq|<li> <a href="$url">$url</a>\n|;
}

print "</ul>\n";
print $query->end_html;

# Untie the data
untie %data;

