# --------------------------------------------------------------------------------- # Author: Dean Stringer # Description/Purpose: # # DB_File is a module which allows Perl programs to make use of # the facilities provided by Berkeley DB # # This demo uses DB_File to manage a list of data records # keyed by a certain value. The index key is a randomly # generated integer in range 0-9 and the script adds 3 new # random records on each pass eventually fully populating # the hash record range of 0-9 # # NOTE: to see the population in action you should delete the # test.db file if there is one in the folder where you run # this script. # # you should have a read about the tie() function in perlfunc # and the perltie manpage # --------------------------------------------------------------------------------- use warnings; use strict; use DB_File; my $fileName = 'test.db'; # need flags 'O_RDWR|O_CREAT' when writing the data file for the 1st time # if only used O_RDWR would get an error if the db file didnt exist my $dbflags = O_CREAT|O_RDWR; our %dbHash; loadData(); getData(); sub getData { # this is an example of use of the object i/f returned by 'tie' through # a var $DB we use to access the BDB cursor/handlers to manipulate # records in the database my $DB = tie %dbHash, "DB_File", $fileName, $dbflags, 0666, $DB_HASH or die "Cant open $fileName: $!"; my ($status, $key, $value); print "\n\nFound:"; for ($status = $DB->seq($key, $value, R_FIRST) ; $status == 0 ; $status = $DB->seq($key, $value, R_NEXT) ) { print "\nkey=$key val=$value"; } undef $DB; # or we get an 'inner refernce exists' warning untie %dbHash; } sub loadData { # unlike getData, here we're directly dealing with the data store using # the 'tie'd hash %dbHash, altho we could have used the OO i/f and its # 'put' method if (tie %dbHash, "DB_File", $fileName, $dbflags, 0666, $DB_HASH) { my $i = 0; for ($i=1; $i<=3; $i++ ) { my $rndNum = int(rand() * 10); print "\nwriting: $rndNum"; $dbHash{$rndNum} = 'this-' . $rndNum; } untie %dbHash; } else { print "Cant open $fileName: $!"; } }