Examples in Perl

Database Files

Here, we discuss a simple way to store and retrieve data as name value pairs from a file.
We use dbmopen to open a database file for reading and writing.
It can be accessed using an associative array.
dbmclose is used to close the file.

The syntax of dbmopen and dbmclose is :

dbmopen %FILE, $path_name, $permission;
dbmclose %FILE;

Here is an example :

#!/usr/bin/perl

dbmopen %FILE, "/home/user/file", 0666;  # opens/creates the file with read and write permissions for user, group and all

$FILE{"name1"} = "value1";        # write a name value pair to the file
$FILE{"name1"} = "anotherValue1;  # Overwrite the previous value
$theValue = $FILE{"name1"};       # Retrieve the value for name1
delete $FILE{"name1"};            # delete a name value pair

The usual associative array specific operations like keys() work here too.
This is a simple, yet powerful method to storing and retrieving name value pairs.
However, there are severe limitations on the number of characters for name and value pairs for the examples as shown here (read an interesting discussion at http://dbforums.com/arch/95/2002/3/328388)
Look for the module DB_File at http://www.cpan.org to work around these limitations


Back to Table of Contents