Friday, November 13, 2009

How to read a Foxpro database with Perl?

I recently had a friend ask me to help them read a FoxPro (dbf, cdx, fpt) database. The only problem was neither of us had FoxpPro or anything that would open and read the file. All we wanted to do was read the data and output plain text. I searched the internet for a free tool to help with this task and I found zilch!!!

I did find things that would let you read the first 50 records, but if you want more you need to buy the product. I found others that places wacky watermarks all other the data until you bought the product. I did some more searching and found the answer. Perl to the rescue!!!

I found a (free) Perl library called XBase that lets you read dbf files with cdx indexes.

First I had to install the XBase perl module. I did this on my iMac like this:

$> sudo perl -MCPAN -e shell
cpan> install DBD::XBase

Once that process was complete, the rest took about 10 minutes.
Here's a sample of the script:

#!/usr/bin/perl

use strict;
use XBase;

my $table = new XBase "MYTABLE.DBF" or die XBase->errstr;
my $cursor = $table->prepare_select("FNAME", "LNAME", "MEMO");

my ($fname, $lname, $memo, $count);

$count = 0;

while ( ($fname, $lname, $memo) = $cursor->fetch) {
print "$count\t$fname\t$lname\t$memo\n";
$count++;
}

That's it! This will print out a tab delimited list of the contents of the database.