Full-Text Searching in Perl

By Tim Kientzle

Dr. Dobb's Journal January 1999

#!/usr/local/bin/perl
require 5;
use DB_File;
use Fcntl;
tie(%index,DB_File,'index.db',
    O_RDONLY, 0, $DB_File::DB_BTREE);
foreach $word (@ARGV) { # Find each word
  $keys = $worddb{lc $word};
  foreach $key (unpack("n*",$keys)) {
    $matches{$key}++;
  }
}
@matches = sort # Rank by total matches
  { $matches{$b} <=> $matches{$a} 
     || $a <=> $b }
  (keys %matches);
foreach $key (@matches) { # Print names
  $name = $index{pack("xn",$key)};
  print "$matches{$key}: $name\n";
}
untie(%index); # Release database

Example 1: A full-text search program.

Back to Article


Copyright © 1999, Dr. Dobb's Journal