If, for example, we want to store the number of Perl objects that exist in our program's data, we can use a variable as a volatile database:

package Book::ObjectCounter;
use strict;
my $object_count = 0;
sub new {
    my $class = shift;
    return bless {  }, $class;

In this example, $object_countserves as a database—it stores the number of currently available objects. When a new object is created this variable increments its value, and when an object gets destroyed the value is decremented.

Now imagine a server, such as mod_perl, where the process can run for months or even years without quitting. Doing this kind of accounting is perfectly suited for the purpose, for if the process quits, all objects are lost anyway, and we probably won't care how many of them were alive when the process terminated.

Here is another example:

$DNS_CACHE{$dns} ||= dns_resolve($dns);
print "Hostname $dns has $DNS_CACHE{$dns} IP\n";

This little code snippet takes the hostname stored in $dns and checks whether we have the corresponding IP address cached in %DNS_CACHE. If not, it resolves it and caches it for later reuse. At the end, it prints out both the hostname and the corresponding IP address.

%DNS_CACHEsatisfies our definition of a database. It's a volatile database, since when the program quits the data disappears. When a mod_perl process quits, the cache is lost, but there is a good chance that we won't regret the loss, since we might want to cache only the latest IP addresses anyway. Now if we want to turn this cache into a non-volatile database, we just need to tie %DNS_CACHE to a DBM file, and we will have a permanent database. We will talk about Database Management (DBM) files in Chapter 19.

In Chapter 18, we will show how you can benefit from this kind of in-process database under mod_perl. We will also show how during a single request different handlers can share data and how data can persist across many requests.