17.1.1. In-Memory Databases in a Single Process
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;
$object_count++;
return bless { }, $class;
}
sub DESTROY {
$object_count--;
}
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.