Creating and Using a Database with Perl

Perl 5 includes packages enabling your Perl scripts to create and modify databases in standard Unix formats. One of these databases can be a more efficient alternative than a flat text file (which Perl handles marvelously), and it will be compatible with other languages, like C.

Perl programmers, like programmers of any other language, typically need to store large amounts of data. For this data to be manageable, it needs to be stored in a conveniently accessible format. It never hurts to make the stored data easy to write, as well.

Even though Perl is an exceptional language for text processing, in many circumstances, a more structured database-like format offers quicker access. In addition, it may also be necessary for a Perl script to read or write a database that is also accessed through a C program.

To accomplish this, the Perl distribution includes packages that give a Perl programmer access to a variety of different database formats available in a Unix environment. These formats include: the Berkeley DB format, the Free Software Foundation's GDBM format and the NDBM format.

Associative Arrays

The associative array (or “hash”) is one of the most powerful data structures available to a Perl programmer. To those familiar with traditional arrays (in C, Pascal or Perl), an associative array can be thought of as an array indexed using an arbitrary string instead of an integer subscript. Basically, an associative array is a data structure that allows the programmer to associate one string—a key—with another—its value.

Here is an example of an associative array that can be used to convert the abbreviated name of a day of the week to its full name.

%days = (
        "Sun", "Sunday",
        "Mon", "Monday",
        "Tue", "Tuesday",
        "Wed", "Wednesday",
        "Thu", "Thursday",
        "Fri", "Friday",
        "Sat", "Saturday"
);

The % in front of the variable name days is used to tell Perl the variable is an associative array. As shown, associative arrays are initialized by using pairs of values that relate to each other.

To access the data stored in an associative array, you can use a syntax similar to the following:

$long_name = $days{"Sun"};

This expression will set the scalar variable long_name to the value associated with the key “Sun”, the string “Sunday” in this example.

You can see already that associative arrays can be a powerful tool for organizing data used inside of a Perl script. This technique can easily be extended to something more useful by creating values made up of more than one field. Take, for instance, this simple address book database where multiple fields in the associative array's value are separated by colons:

$phone_db = (
        "Bill Jones", "123 West Avenue:New York, NY:12345",
        "Jane Smith", "6789 1st Street:Chicago, IL:56789"
);

New entries in this database can be added with an expression like:

$phone_db{"Bill Smith"} = join(":", $street, $city, $zip_code);
Data can be extracted from this simple database with an expression like:
($street, $city, $zip_code) = split(/:/, $phone_db{"Bill Smith"});
As you can see, these arrays come in very handy for manipulating data inside a Perl script. However, how can we export this data easily to a file so our scripts or other programs can access the data? One simple method would be to use a text file with the fields of our database separated by colons. This method would make writing out the database from our Perl script very simple. It could be done using a piece of code like the following:
while (($name, $record) = each %phone_db) {
        print "$name:$record\n";
}
This method does not lend itself well to performing a search through the file, as we would need to read, on average, half the lines in the file in order to find the record we are seeking. In addition, writing code to search such a file in other languages (C, for instance) may not be as simple as the Perl script we have written.

To solve this problem, Perl supports “binding” associative arrays to the various types of database formats mentioned above. This allows a Perl programmer to create, access and update databases in the popular Unix database formats as easily as performing operations on an associative array.

Database Support in Perl

Perl version 5 includes a set of “packages” that manipulate the various database formats. These packages are:

  • DB_File—for Berkeley DB databases

  • GDBM_File—for the Free Software Foundation's GDBM databases

  • NDBM_File

  • ODBM_File

  • SDBM_File

To use any of these database packages, a Perl programmer must include the package at the beginning of the script using the following statement:

use DB_File;
In addition, the Fcntl package also needs to be included. This is accomplished by including the following at the beginning of the script:
use Fcntl;
Man pages are included in the Perl distribution for each of these packages. For simplicity's sake, only the DB_File package and its associated Berkeley DB databases are discussed in this article.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

hjguyguygudcfgdst

Anonymous's picture

hjguyguygudcfgdst

Nice explanation . It helped

Anonymous's picture

Nice explanation . It helped me a lot in getting started with databases. thanks a lot.

Retrieval of databases

jamesmicheallay's picture

Well, I've learned how to encode information to a database with this article, but I still don't understand database retrieval with DB_File yet. How would you write one program to encode the information and another program to retrieve it (to clear confusion because it seems like you have to encode the database everytime you want to retrieve from it, completely defeating the purpose of saving).

thanks

Pradeep Kota's picture

Nice explanation. It helped me a lot in getting started with databases. thanks a lot. :)

cheers,
Kota.

Previous comment about anonymous hash

Anonymous's picture

It appears this was a typo, should be %phone_db(), since there is no mention of this being a scalar reference of an anonymous hash, but a hash container. I am assuming this is the case, since all other examples do not use a dereference of the hash, they would have been $$phone_db{"key"}

Incorrect syntax in hash formation

Anonymous's picture

The example under the Associative Arrays heading that shows how to store an anonymous hash's reference in a scalar is incorrect; instead of $phone_db=( ... ), it should be $phone_db={ ... } (curly braces, not parens). FWIW, this is a very common misteak 8-}

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix