Going Off the Beaten DB Path (cont'd)

T-i-e Function Does the Heavy Lifting

As you can see, the heavy lifting here is done by the tie function. Let's examine it more closely. The hash %hash exists only for the duration of the program, but the file myDB will endure after the program finishes. A look at the present working directory reveals that a file called myDB has been created, but don't bother trying to read it—it's binary. It is, however, a regular self-contained file, and you can copy it, change its permissions, send it to another server, or what have you, and the data will remain unchanged.

In this context, the tie function has several default parameters that are implied in the above usage. To make all the parameters explicit, I would write the above tie function like so:

tie %hash, "DB_File", "myDB", O_RDWR|O_CREAT, 0666, $DB_HASH;

The fourth and fifth parameters set the mode for the created file, and the sixth sets the file format. DB_HASH is one of three file formats available to DB_File, DB_BTREE and DB_RECNO being the other two. DB_HASH is the simplest and most straightforward of the three-it's very similar to a standard Perl associative array, with data stored in key-value pairs.


tie %hash, "DB_File", "myDB"
  or die "Could not read file 'myDB': $!\n";

foreach $key (keys %hash) {
  print "$key => $hash{$key}\n";
}

untie %hash;

Once %hash has been tied to the file myDB, all the standard Perl hash functions are available, including keys as used above. The above code will output the following:


key1 => value1
key3 => value3
key2 => value2

Note that the values are returned in an apparently random order. To keep the values in a specified order, it's necessary to use the DB_BTREE file format.

  
Next: Won't Break a Sweat Building a Hash

1 Introduction 2 Designed for Programmers, not DBAs 3 Taking Berkeley to Task
4 T-i-e Function Does the Heavy Lifting 5 Won't Break a Sweat Building a Hash 6 Assigning Multiple Values to a Single Key


Get Help - Search Tips
 

Sleepycat Software

DevX e-Learning: Relational Database Concepts

DevX's Open Source Zone

DevX's Open Source.General discussion group

 TALK BACK
Have you ever worked with an open-source database? Has it served your purpose well? How does it compare with conventional DBs? Go here to start or join the discussion.
Click here to Join


Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map
Jupiterweb networks

internet.comearthweb.comDevx.comClickZ

Search Jupiterweb:

Jupitermedia Corporation has four divisions:
JupiterWeb, JupiterResearch, JupiterEvents, and JupiterImages

Copyright 2004 Jupitermedia Corporation All Rights Reserved.
Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Jupitermedia Corporate Info | Newsletters | Tech Jobs | E-mail Offers