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 itit'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.