[ Top page ]

« Circular layout of radio buttons to a Web page using Perl | Main | Simplified XML interface using Perl -- conversion of table-style data representation between hash and XML »

Database

Perl database (tie) generation from text

A simplified database can be handled easily using tie() of Perl, instead of using heavy-duty databases such as relational databases. When using tie(), hashes can be tied to an external database and the hashes can be permanent. However, in contrast to heavy-duty databases, it is not possible to write to the database in parallel and the performance is probably lower. So it is suited for prototypes but not suted for real use.

Microsoft Excel is often used when creating a data group such as a database or data to be entered to a database. So, we often want to enter data created by Excel or another program, for example, by outputting it to a tab-separated text. The following program is an example for such task.

The following program inputs a sequence of records that contains four fields separated by white-space characters such as tabs, and enters them into a simplified database. In this database, the records can be searched by using the contents of first field as keys. The keys must be unique (but the uniqueness is not checked here).




############################################################################
#
#	Text to DBM converter
#
############################################################################

use strict 'subs';
use strict 'refs';

use SDBM_File;

use Fcntl;

my $FileName = "C:\DB_File";

sub error($) {
    my ($message) = @_;
    print STDERR "Error: $message\n";
}


my %db;

tie(%db, 'SDBM_File', $FileName, O_RDWR | O_CREAT, 0666) ||
    error("Can't open database file!");

%db = ();

$| = 1;
print "Input file name: ";
my $file = <>;
chomp $file;
open(INPUT, $file);
while (<INPUT>) {
    if (/^(\w+)\s+(\w+)\s+(\w+)\s+(\w+)/) {
	my $A = $1;
	my $B = $2;
	my $C = $3;
	my $D = $4;
	print "A=${A} B=${B} C=${C} D=${D}\n";
	$db{A} = "${B}\t${C}\t${D}";
    } else {
	error("Syntax error: $_");
    };
};

untie(%db);

1;
Keywords:

TrackBack

TrackBack URL for this entry:
https://www.kanadas.com/mt/mt-tb.cgi/1645

Post a comment

About

This page contains a single entry from the blog posted on November 16, 2007 12:21 AM.

Many more can be found on the main index page or by looking through the archives.

Creative Commons License
This weblog is licensed under a Creative Commons License.
Powered by Movable Type