Creating and Using a Database with Perl
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.
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.
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.
Trending Topics
| Make TV Awesome with Bluecop | May 16, 2012 |
| Hack and / - Password Cracking with GPUs, Part I: the Setup | May 15, 2012 |
| An Introduction to Application Development with Catalyst and Perl | May 14, 2012 |
| Cryptocurrency: Your Total Cost Is 01001010010 | May 09, 2012 |
| HTML5 for Audio Applications | May 07, 2012 |
| May 2012 Issue of Linux Journal: Programming | May 02, 2012 |
- Hack and / - Password Cracking with GPUs, Part I: the Setup
- An Introduction to Application Development with Catalyst and Perl
- Validate an E-Mail Address with PHP, the Right Way
- Make TV Awesome with Bluecop
- Monitoring Hard Disks with SMART
- Which one is the Best Free and Paid PDF editor for Mac
- Examining Load Average
- Readers' Choice Awards 2011
- Bash Regular Expressions
- Building an Ultra-Low-Power File Server with the Trim-Slice
- It's true that maintaining
2 hours 12 min ago - as powerful as anything the
7 hours 49 min ago - Excellent!
11 hours 11 min ago - You can mount ext2 and ext3
18 hours 59 min ago - Awsome Post
1 day 7 hours ago - Math Worksheets
1 day 11 hours ago - Healthy eating effective weight loss of p57
1 day 17 hours ago - Good work, looking for more!
1 day 17 hours ago - I’ve been reading a number of
1 day 18 hours ago - With freeware SKim, You can
1 day 18 hours ago






Comments
hjguyguygudcfgdst
hjguyguygudcfgdst
Nice explanation . It helped
Nice explanation . It helped me a lot in getting started with databases. thanks a lot.
Retrieval of databases
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
Nice explanation. It helped me a lot in getting started with databases. thanks a lot. :)
cheers,
Kota.
Previous comment about anonymous hash
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
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-}