For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > December 2007 > Re: Effective search of text file









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Effective search of text file
Chas. Owens

2007-12-12, 8:00 am

On Dec 11, 2007 6:26 PM, Why Tea <ytlim1@gmail.com> wrote:
> I have a text file of acronyms of about 2MB, I would like to write a
> cgi script to allow users to query for any acronym in the text file.
> What is the best way of implementing it (i.e. taking the acronym as a
> key to search for the expanded text)?
>
> /Why Tea


It sounds like you are looking for a DBM file. Perl lets you tie a
hash to one so access to it is as easy as access to a hash. You can
read more about DBM files in perldoc DB_File and perldoc AnyDBM_File
or http://perldoc.perl.org/DB_File.html and
http://perldoc.perl.org/AnyDBM_File.html.


cowens@amans:~$ cat acronyms.txt
lol => laughing out loud
brb => be right back
timtowtdi => there is more than on way to do it
cowens@amans:~$ cat import.pl
#!/usr/bin/perl

use strict;
use warnings;
use DB_File;

my %dict;
tie %dict, 'DB_File', "dictionary.db"
or die "could not tie/create dictionary.db: $!";

#import format is
#key => definition
while (<> ) {
chomp;
my ($key, $def) = split ' => ';
$dict{$key} = $def;
}
cowens@amans:~$ ./import.pl acronyms.txt
cowens@amans:~$ cat lookup.pl
#!/usr/bin/perl

use strict;
use warnings;
use DB_File;

my %dict;
tie %dict, 'DB_File', "dictionary.db"
or die "could not tie/create dictionary.db: $!";

for my $query (@ARGV) {
if (exists $dict{$query}) {
print "$query expands to $dict{$query}\n";
} else {
print "sorry, I don't know $query\n";
}
}
cowens@amans:~$ ./lookup.pl timtowtdi rofl
timtowtdi expands to there is more than on way to do it
sorry, I don't know rofl

You might want to convert the case of the key to either all upper case
or all lower case with uc or lc before storing or looking up the key
if you want to let them search in a case insensitive manner.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com