1 # DB_File.pm -- Perl 5 interface to Berkeley DB
3 # written by Paul Marquess (pmqs@cpan.org)
4 # last modified 28th October 2007
7 # Copyright (c) 1995-2007 Paul Marquess. All rights reserved.
8 # This program is free software; you can redistribute it and/or
9 # modify it under the same terms as Perl itself.
12 package DB_File::HASHINFO ;
20 @DB_File::HASHINFO::ISA = qw(Tie::Hash);
53 return $self->{GOT}{$key} if exists $self->{VALID}{$key} ;
56 croak "${pkg}::FETCH - Unknown element '$key'" ;
66 my $type = $self->{VALID}{$key};
70 croak "Key '$key' not associated with a code reference"
71 if $type == 2 && !ref $value && ref $value ne 'CODE';
72 $self->{GOT}{$key} = $value ;
77 croak "${pkg}::STORE - Unknown element '$key'" ;
85 if ( exists $self->{VALID}{$key} )
87 delete $self->{GOT}{$key} ;
92 croak "DB_File::HASHINFO::DELETE - Unknown element '$key'" ;
100 exists $self->{VALID}{$key} ;
108 croak ref($self) . " does not define the method ${method}" ;
111 sub FIRSTKEY { my $self = shift ; $self->NotHere("FIRSTKEY") }
112 sub NEXTKEY { my $self = shift ; $self->NotHere("NEXTKEY") }
113 sub CLEAR { my $self = shift ; $self->NotHere("CLEAR") }
115 package DB_File::RECNOINFO ;
120 @DB_File::RECNOINFO::ISA = qw(DB_File::HASHINFO) ;
126 bless { VALID => { map {$_, 1}
127 qw( bval cachesize psize flags lorder reclen bfname )
133 package DB_File::BTREEINFO ;
138 @DB_File::BTREEINFO::ISA = qw(DB_File::HASHINFO) ;
163 our ($VERSION, @ISA, @EXPORT, $AUTOLOAD, $DB_BTREE, $DB_HASH, $DB_RECNO);
164 our ($db_version, $use_XSLoader, $splice_end_array, $Error);
168 $VERSION = "1.816_1" ;
171 local $SIG{__WARN__} = sub {$splice_end_array = "@_";};
172 my @a =(1); splice(@a, 3);
174 ($splice_end_array =~ /^splice\(\) offset past end of array at /);
177 #typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
178 $DB_BTREE = new DB_File::BTREEINFO ;
179 $DB_HASH = new DB_File::HASHINFO ;
180 $DB_RECNO = new DB_File::RECNOINFO ;
187 { local $SIG{__DIE__} ; eval { require XSLoader } ; }
192 @ISA = qw(DynaLoader);
196 push @ISA, qw(Tie::Hash Exporter);
198 $DB_BTREE $DB_HASH $DB_RECNO
233 ($constname = $AUTOLOAD) =~ s/.*:://;
234 my ($error, $val) = constant($constname);
235 Carp::croak $error if $error;
237 *{$AUTOLOAD} = sub { $val };
243 # Make all Fcntl O_XXX constants available for importing
245 my @O = grep /^O_/, @Fcntl::EXPORT;
246 Fcntl->import(@O); # first we import what we want to export
251 { XSLoader::load("DB_File", $VERSION)}
253 { bootstrap DB_File $VERSION }
255 # Preloaded methods go here. Autoload methods go after __END__, and are
256 # processed by the autosplit program.
258 sub tie_hash_or_array
261 my $tieHASH = ( (caller(1))[3] =~ /TIEHASH/ ) ;
264 $arg[1] = File::Spec->rel2abs($arg[1])
267 $arg[4] = tied %{ $arg[4] }
268 if @arg >= 5 && ref $arg[4] && $arg[4] =~ /=HASH/ && tied %{ $arg[4] } ;
270 $arg[2] = O_CREAT()|O_RDWR() if @arg >=3 && ! defined $arg[2];
271 $arg[3] = 0666 if @arg >=4 && ! defined $arg[3];
273 # make recno in Berkeley DB version 2 (or better) work like
274 # recno in version 1.
275 if ($db_version >= 4 and ! $tieHASH) {
276 $arg[2] |= O_CREAT();
279 if ($db_version > 1 and defined $arg[4] and $arg[4] =~ /RECNO/ and
280 $arg[1] and ! -e $arg[1]) {
281 open(FH, ">$arg[1]") or return undef ;
283 chmod $arg[3] ? $arg[3] : 0666 , $arg[1] ;
286 DoTie_($tieHASH, @arg) ;
291 tie_hash_or_array(@_) ;
296 tie_hash_or_array(@_) ;
304 my $status = $self->seq($key, $value, R_FIRST());
307 while ($status == 0) {
309 $status = $self->seq($key, $value, R_NEXT());
311 foreach $key (reverse @keys) {
312 my $s = $self->del($key);
322 my $current_length = $self->length() ;
324 if ($length < $current_length) {
326 for ($key = $current_length - 1 ; $key >= $length ; -- $key)
329 elsif ($length > $current_length) {
330 $self->put($length-1, "") ;
339 if (not defined $offset) {
340 warnings::warnif('uninitialized', 'Use of uninitialized value in splice');
344 my $length = @_ ? shift : 0;
345 # Carping about definedness comes _after_ the OFFSET sanity check.
346 # This is so we get the same error messages as Perl's splice().
351 my $size = $self->FETCHSIZE();
353 # 'If OFFSET is negative then it start that far from the end of
357 my $new_offset = $size + $offset;
358 if ($new_offset < 0) {
359 die "Modification of non-creatable array value attempted, "
360 . "subscript $offset";
362 $offset = $new_offset;
365 if (not defined $length) {
366 warnings::warnif('uninitialized', 'Use of uninitialized value in splice');
370 if ($offset > $size) {
372 warnings::warnif('misc', 'splice() offset past end of array')
373 if $splice_end_array;
376 # 'If LENGTH is omitted, removes everything from OFFSET onward.'
377 if (not defined $length) {
378 $length = $size - $offset;
381 # 'If LENGTH is negative, leave that many elements off the end of
385 $length = $size - $offset + $length;
388 # The user must have specified a length bigger than the
389 # length of the array passed in. But perl's splice()
390 # doesn't catch this, it just behaves as for length=0.
396 if ($length > $size - $offset) {
397 $length = $size - $offset;
400 # $num_elems holds the current number of elements in the database.
401 my $num_elems = $size;
403 # 'Removes the elements designated by OFFSET and LENGTH from an
407 foreach (0 .. $length - 1) {
409 my $status = $self->get($offset, $old);
411 my $msg = "error from Berkeley DB on get($offset, \$old)";
413 $msg .= ' (no such element?)';
416 $msg .= ": error status $status";
417 if (defined $! and $! ne '') {
418 $msg .= ", message $!";
425 $status = $self->del($offset);
427 my $msg = "error from Berkeley DB on del($offset)";
429 $msg .= ' (no such element?)';
432 $msg .= ": error status $status";
433 if (defined $! and $! ne '') {
434 $msg .= ", message $!";
443 # ...'and replaces them with the elements of LIST, if any.'
445 while (defined (my $elem = shift @list)) {
448 if ($pos >= $num_elems) {
449 $status = $self->put($pos, $elem);
452 $status = $self->put($pos, $elem, $self->R_IBEFORE);
456 my $msg = "error from Berkeley DB on put($pos, $elem, ...)";
458 $msg .= ' (no such element?)';
461 $msg .= ", error status $status";
462 if (defined $! and $! ne '') {
463 $msg .= ", message $!";
469 die "pos unexpectedly changed from $old_pos to $pos with R_IBEFORE"
477 # 'In list context, returns the elements removed from the
482 elsif (defined wantarray and not wantarray) {
483 # 'In scalar context, returns the last element removed, or
484 # undef if no elements are removed.'
487 my $last = pop @removed;
494 elsif (not defined wantarray) {
499 sub ::DB_File::splice { &SPLICE }
503 croak "Usage: \$db->find_dup(key,value)\n"
507 my ($origkey, $value_wanted) = @_ ;
508 my ($key, $value) = ($origkey, 0);
511 for ($status = $db->seq($key, $value, R_CURSOR() ) ;
513 $status = $db->seq($key, $value, R_NEXT() ) ) {
515 return 0 if $key eq $origkey and $value eq $value_wanted ;
523 croak "Usage: \$db->del_dup(key,value)\n"
527 my ($key, $value) = @_ ;
528 my ($status) = $db->find_dup($key, $value) ;
529 return $status if $status != 0 ;
531 $status = $db->del($key, R_CURSOR() ) ;
537 croak "Usage: \$db->get_dup(key [,flag])\n"
538 unless @_ == 2 or @_ == 3 ;
545 my $wantarray = wantarray ;
551 # iterate through the database until either EOF ($status == 0)
552 # or a different key is encountered ($key ne $origkey).
553 for ($status = $db->seq($key, $value, R_CURSOR()) ;
554 $status == 0 and $key eq $origkey ;
555 $status = $db->seq($key, $value, R_NEXT()) ) {
557 # save the value or count number of matches
560 { ++ $values{$value} }
562 { push (@values, $value) }
569 return ($wantarray ? ($flag ? %values : @values) : $counter) ;
578 DB_File - Perl5 access to Berkeley DB version 1.x
584 [$X =] tie %hash, 'DB_File', [$filename, $flags, $mode, $DB_HASH] ;
585 [$X =] tie %hash, 'DB_File', $filename, $flags, $mode, $DB_BTREE ;
586 [$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ;
588 $status = $X->del($key [, $flags]) ;
589 $status = $X->put($key, $value [, $flags]) ;
590 $status = $X->get($key, $value [, $flags]) ;
591 $status = $X->seq($key, $value, $flags) ;
592 $status = $X->sync([$flags]) ;
596 $count = $X->get_dup($key) ;
597 @list = $X->get_dup($key) ;
598 %list = $X->get_dup($key, 1) ;
599 $status = $X->find_dup($key, $value) ;
600 $status = $X->del_dup($key, $value) ;
608 @r = $X->splice(offset, length, elements);
611 $old_filter = $db->filter_store_key ( sub { ... } ) ;
612 $old_filter = $db->filter_store_value( sub { ... } ) ;
613 $old_filter = $db->filter_fetch_key ( sub { ... } ) ;
614 $old_filter = $db->filter_fetch_value( sub { ... } ) ;
621 B<DB_File> is a module which allows Perl programs to make use of the
622 facilities provided by Berkeley DB version 1.x (if you have a newer
623 version of DB, see L<Using DB_File with Berkeley DB version 2 or greater>).
624 It is assumed that you have a copy of the Berkeley DB manual pages at
625 hand when reading this documentation. The interface defined here
626 mirrors the Berkeley DB interface closely.
628 Berkeley DB is a C library which provides a consistent interface to a
629 number of database formats. B<DB_File> provides an interface to all
630 three of the database types currently supported by Berkeley DB.
638 This database type allows arbitrary key/value pairs to be stored in data
639 files. This is equivalent to the functionality provided by other
640 hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
641 the files created using DB_HASH are not compatible with any of the
642 other packages mentioned.
644 A default hashing algorithm, which will be adequate for most
645 applications, is built into Berkeley DB. If you do need to use your own
646 hashing algorithm it is possible to write your own in Perl and have
647 B<DB_File> use it instead.
651 The btree format allows arbitrary key/value pairs to be stored in a
652 sorted, balanced binary tree.
654 As with the DB_HASH format, it is possible to provide a user defined
655 Perl routine to perform the comparison of keys. By default, though, the
656 keys are stored in lexical order.
660 DB_RECNO allows both fixed-length and variable-length flat text files
661 to be manipulated using the same key/value pair interface as in DB_HASH
662 and DB_BTREE. In this case the key will consist of a record (line)
667 =head2 Using DB_File with Berkeley DB version 2 or greater
669 Although B<DB_File> is intended to be used with Berkeley DB version 1,
670 it can also be used with version 2, 3 or 4. In this case the interface is
671 limited to the functionality provided by Berkeley DB 1.x. Anywhere the
672 version 2 or greater interface differs, B<DB_File> arranges for it to work
673 like version 1. This feature allows B<DB_File> scripts that were built
674 with version 1 to be migrated to version 2 or greater without any changes.
676 If you want to make use of the new features available in Berkeley DB
677 2.x or greater, use the Perl module B<BerkeleyDB> instead.
679 B<Note:> The database file format has changed multiple times in Berkeley
680 DB version 2, 3 and 4. If you cannot recreate your databases, you
681 must dump any existing databases with either the C<db_dump> or the
682 C<db_dump185> utility that comes with Berkeley DB.
683 Once you have rebuilt DB_File to use Berkeley DB version 2 or greater,
684 your databases can be recreated using C<db_load>. Refer to the Berkeley DB
685 documentation for further details.
687 Please read L<"COPYRIGHT"> before using version 2.x or greater of Berkeley
690 =head2 Interface to Berkeley DB
692 B<DB_File> allows access to Berkeley DB files using the tie() mechanism
693 in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
694 allows B<DB_File> to access Berkeley DB files using either an
695 associative array (for DB_HASH & DB_BTREE file types) or an ordinary
696 array (for the DB_RECNO file type).
698 In addition to the tie() interface, it is also possible to access most
699 of the functions provided in the Berkeley DB API directly.
700 See L<THE API INTERFACE>.
702 =head2 Opening a Berkeley DB Database File
704 Berkeley DB uses the function dbopen() to open or create a database.
705 Here is the C prototype for dbopen():
708 dbopen (const char * file, int flags, int mode,
709 DBTYPE type, const void * openinfo)
711 The parameter C<type> is an enumeration which specifies which of the 3
712 interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
713 Depending on which of these is actually chosen, the final parameter,
714 I<openinfo> points to a data structure which allows tailoring of the
715 specific interface method.
717 This interface is handled slightly differently in B<DB_File>. Here is
718 an equivalent call using B<DB_File>:
720 tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
722 The C<filename>, C<flags> and C<mode> parameters are the direct
723 equivalent of their dbopen() counterparts. The final parameter $DB_HASH
724 performs the function of both the C<type> and C<openinfo> parameters in
727 In the example above $DB_HASH is actually a pre-defined reference to a
728 hash object. B<DB_File> has three of these pre-defined references.
729 Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
731 The keys allowed in each of these pre-defined references is limited to
732 the names used in the equivalent C structure. So, for example, the
733 $DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
734 C<ffactor>, C<hash>, C<lorder> and C<nelem>.
736 To change one of these elements, just assign to it like this:
738 $DB_HASH->{'cachesize'} = 10000 ;
740 The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
741 usually adequate for most applications. If you do need to create extra
742 instances of these objects, constructors are available for each file
745 Here are examples of the constructors and the valid options available
746 for DB_HASH, DB_BTREE and DB_RECNO respectively.
748 $a = new DB_File::HASHINFO ;
756 $b = new DB_File::BTREEINFO ;
766 $c = new DB_File::RECNOINFO ;
775 The values stored in the hashes above are mostly the direct equivalent
776 of their C counterpart. Like their C counterparts, all are set to a
777 default values - that means you don't have to set I<all> of the
778 values when you only want to change one. Here is an example:
780 $a = new DB_File::HASHINFO ;
781 $a->{'cachesize'} = 12345 ;
782 tie %y, 'DB_File', "filename", $flags, 0777, $a ;
784 A few of the options need extra discussion here. When used, the C
785 equivalent of the keys C<hash>, C<compare> and C<prefix> store pointers
786 to C functions. In B<DB_File> these keys are used to store references
787 to Perl subs. Below are templates for each of the subs:
793 # return the hash value for $data
799 my ($key, $key2) = @_ ;
801 # return 0 if $key1 eq $key2
802 # -1 if $key1 lt $key2
803 # 1 if $key1 gt $key2
804 return (-1 , 0 or 1) ;
809 my ($key, $key2) = @_ ;
811 # return number of bytes of $key2 which are
812 # necessary to determine that it is greater than $key1
816 See L<Changing the BTREE sort order> for an example of using the
819 If you are using the DB_RECNO interface and you intend making use of
820 C<bval>, you should check out L<The 'bval' Option>.
822 =head2 Default Parameters
824 It is possible to omit some or all of the final 4 parameters in the
825 call to C<tie> and let them take default values. As DB_HASH is the most
826 common file format used, the call:
828 tie %A, "DB_File", "filename" ;
832 tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
834 It is also possible to omit the filename parameter as well, so the
841 tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
843 See L<In Memory Databases> for a discussion on the use of C<undef>
844 in place of a filename.
846 =head2 In Memory Databases
848 Berkeley DB allows the creation of in-memory databases by using NULL
849 (that is, a C<(char *)0> in C) in place of the filename. B<DB_File>
850 uses C<undef> instead of NULL to provide this functionality.
854 The DB_HASH file format is probably the most commonly used of the three
855 file formats that B<DB_File> supports. It is also very straightforward
858 =head2 A Simple Example
860 This example shows how to create a database, add key/value pairs to the
861 database, delete keys/value pairs and finally how to enumerate the
862 contents of the database.
870 tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0666, $DB_HASH
871 or die "Cannot open file 'fruit': $!\n";
873 # Add a few key/value pairs to the file
874 $h{"apple"} = "red" ;
875 $h{"orange"} = "orange" ;
876 $h{"banana"} = "yellow" ;
877 $h{"tomato"} = "red" ;
879 # Check for existence of a key
880 print "Banana Exists\n\n" if $h{"banana"} ;
882 # Delete a key/value pair.
885 # print the contents of the file
886 while (($k, $v) = each %h)
887 { print "$k -> $v\n" }
899 Note that the like ordinary associative arrays, the order of the keys
900 retrieved is in an apparently random order.
904 The DB_BTREE format is useful when you want to store data in a given
905 order. By default the keys will be stored in lexical order, but as you
906 will see from the example shown in the next section, it is very easy to
907 define your own sorting function.
909 =head2 Changing the BTREE sort order
911 This script shows how to override the default sorting algorithm that
912 BTREE uses. Instead of using the normal lexical ordering, a case
913 insensitive compare function will be used.
923 my ($key1, $key2) = @_ ;
924 "\L$key1" cmp "\L$key2" ;
927 # specify the Perl sub that will do the comparison
928 $DB_BTREE->{'compare'} = \&Compare ;
931 tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0666, $DB_BTREE
932 or die "Cannot open file 'tree': $!\n" ;
934 # Add a key/value pair to the file
935 $h{'Wall'} = 'Larry' ;
936 $h{'Smith'} = 'John' ;
937 $h{'mouse'} = 'mickey' ;
938 $h{'duck'} = 'donald' ;
943 # Cycle through the keys printing them in order.
944 # Note it is not necessary to sort the keys as
945 # the btree will have kept them in order automatically.
951 Here is the output from the code above.
957 There are a few point to bear in mind if you want to change the
958 ordering in a BTREE database:
964 The new compare function must be specified when you create the database.
968 You cannot change the ordering once the database has been created. Thus
969 you must use the same compare function every time you access the
974 Duplicate keys are entirely defined by the comparison function.
975 In the case-insensitive example above, the keys: 'KEY' and 'key'
976 would be considered duplicates, and assigning to the second one
977 would overwrite the first. If duplicates are allowed for (with the
978 R_DUP flag discussed below), only a single copy of duplicate keys
979 is stored in the database --- so (again with example above) assigning
980 three values to the keys: 'KEY', 'Key', and 'key' would leave just
981 the first key: 'KEY' in the database with three values. For some
982 situations this results in information loss, so care should be taken
983 to provide fully qualified comparison functions when necessary.
984 For example, the above comparison routine could be modified to
985 additionally compare case-sensitively if two keys are equal in the
986 case insensitive comparison:
989 my($key1, $key2) = @_;
990 lc $key1 cmp lc $key2 ||
994 And now you will only have duplicates when the keys themselves
995 are truly the same. (note: in versions of the db library prior to
996 about November 1996, such duplicate keys were retained so it was
997 possible to recover the original keys in sets of keys that
1003 =head2 Handling Duplicate Keys
1005 The BTREE file type optionally allows a single key to be associated
1006 with an arbitrary number of values. This option is enabled by setting
1007 the flags element of C<$DB_BTREE> to R_DUP when creating the database.
1009 There are some difficulties in using the tied hash interface if you
1010 want to manipulate a BTREE database with duplicate keys. Consider this
1017 my ($filename, %h) ;
1019 $filename = "tree" ;
1022 # Enable duplicate records
1023 $DB_BTREE->{'flags'} = R_DUP ;
1025 tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1026 or die "Cannot open $filename: $!\n";
1028 # Add some key/value pairs to the file
1029 $h{'Wall'} = 'Larry' ;
1030 $h{'Wall'} = 'Brick' ; # Note the duplicate key
1031 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
1032 $h{'Smith'} = 'John' ;
1033 $h{'mouse'} = 'mickey' ;
1035 # iterate through the associative array
1036 # and print each key/value pair.
1037 foreach (sort keys %h)
1038 { print "$_ -> $h{$_}\n" }
1050 As you can see 3 records have been successfully created with key C<Wall>
1051 - the only thing is, when they are retrieved from the database they
1052 I<seem> to have the same value, namely C<Larry>. The problem is caused
1053 by the way that the associative array interface works. Basically, when
1054 the associative array interface is used to fetch the value associated
1055 with a given key, it will only ever retrieve the first value.
1057 Although it may not be immediately obvious from the code above, the
1058 associative array interface can be used to write values with duplicate
1059 keys, but it cannot be used to read them back from the database.
1061 The way to get around this problem is to use the Berkeley DB API method
1062 called C<seq>. This method allows sequential access to key/value
1063 pairs. See L<THE API INTERFACE> for details of both the C<seq> method
1064 and the API in general.
1066 Here is the script above rewritten using the C<seq> API method.
1072 my ($filename, $x, %h, $status, $key, $value) ;
1074 $filename = "tree" ;
1077 # Enable duplicate records
1078 $DB_BTREE->{'flags'} = R_DUP ;
1080 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1081 or die "Cannot open $filename: $!\n";
1083 # Add some key/value pairs to the file
1084 $h{'Wall'} = 'Larry' ;
1085 $h{'Wall'} = 'Brick' ; # Note the duplicate key
1086 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
1087 $h{'Smith'} = 'John' ;
1088 $h{'mouse'} = 'mickey' ;
1090 # iterate through the btree using seq
1091 # and print each key/value pair.
1093 for ($status = $x->seq($key, $value, R_FIRST) ;
1095 $status = $x->seq($key, $value, R_NEXT) )
1096 { print "$key -> $value\n" }
1109 This time we have got all the key/value pairs, including the multiple
1110 values associated with the key C<Wall>.
1112 To make life easier when dealing with duplicate keys, B<DB_File> comes with
1113 a few utility methods.
1115 =head2 The get_dup() Method
1117 The C<get_dup> method assists in
1118 reading duplicate values from BTREE databases. The method can take the
1121 $count = $x->get_dup($key) ;
1122 @list = $x->get_dup($key) ;
1123 %list = $x->get_dup($key, 1) ;
1125 In a scalar context the method returns the number of values associated
1126 with the key, C<$key>.
1128 In list context, it returns all the values which match C<$key>. Note
1129 that the values will be returned in an apparently random order.
1131 In list context, if the second parameter is present and evaluates
1132 TRUE, the method returns an associative array. The keys of the
1133 associative array correspond to the values that matched in the BTREE
1134 and the values of the array are a count of the number of times that
1135 particular value occurred in the BTREE.
1137 So assuming the database created above, we can use C<get_dup> like
1144 my ($filename, $x, %h) ;
1146 $filename = "tree" ;
1148 # Enable duplicate records
1149 $DB_BTREE->{'flags'} = R_DUP ;
1151 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1152 or die "Cannot open $filename: $!\n";
1154 my $cnt = $x->get_dup("Wall") ;
1155 print "Wall occurred $cnt times\n" ;
1157 my %hash = $x->get_dup("Wall", 1) ;
1158 print "Larry is there\n" if $hash{'Larry'} ;
1159 print "There are $hash{'Brick'} Brick Walls\n" ;
1161 my @list = sort $x->get_dup("Wall") ;
1162 print "Wall => [@list]\n" ;
1164 @list = $x->get_dup("Smith") ;
1165 print "Smith => [@list]\n" ;
1167 @list = $x->get_dup("Dog") ;
1168 print "Dog => [@list]\n" ;
1173 Wall occurred 3 times
1175 There are 2 Brick Walls
1176 Wall => [Brick Brick Larry]
1180 =head2 The find_dup() Method
1182 $status = $X->find_dup($key, $value) ;
1184 This method checks for the existence of a specific key/value pair. If the
1185 pair exists, the cursor is left pointing to the pair and the method
1186 returns 0. Otherwise the method returns a non-zero value.
1188 Assuming the database from the previous example:
1194 my ($filename, $x, %h, $found) ;
1196 $filename = "tree" ;
1198 # Enable duplicate records
1199 $DB_BTREE->{'flags'} = R_DUP ;
1201 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1202 or die "Cannot open $filename: $!\n";
1204 $found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
1205 print "Larry Wall is $found there\n" ;
1207 $found = ( $x->find_dup("Wall", "Harry") == 0 ? "" : "not") ;
1208 print "Harry Wall is $found there\n" ;
1216 Harry Wall is not there
1219 =head2 The del_dup() Method
1221 $status = $X->del_dup($key, $value) ;
1223 This method deletes a specific key/value pair. It returns
1224 0 if they exist and have been deleted successfully.
1225 Otherwise the method returns a non-zero value.
1227 Again assuming the existence of the C<tree> database
1233 my ($filename, $x, %h, $found) ;
1235 $filename = "tree" ;
1237 # Enable duplicate records
1238 $DB_BTREE->{'flags'} = R_DUP ;
1240 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1241 or die "Cannot open $filename: $!\n";
1243 $x->del_dup("Wall", "Larry") ;
1245 $found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
1246 print "Larry Wall is $found there\n" ;
1253 Larry Wall is not there
1255 =head2 Matching Partial Keys
1257 The BTREE interface has a feature which allows partial keys to be
1258 matched. This functionality is I<only> available when the C<seq> method
1259 is used along with the R_CURSOR flag.
1261 $x->seq($key, $value, R_CURSOR) ;
1263 Here is the relevant quote from the dbopen man page where it defines
1264 the use of the R_CURSOR flag with seq:
1266 Note, for the DB_BTREE access method, the returned key is not
1267 necessarily an exact match for the specified key. The returned key
1268 is the smallest key greater than or equal to the specified key,
1269 permitting partial key matches and range searches.
1271 In the example script below, the C<match> sub uses this feature to find
1272 and print the first matching key/value pair given a partial key.
1279 my ($filename, $x, %h, $st, $key, $value) ;
1285 my $orig_key = $key ;
1286 $x->seq($key, $value, R_CURSOR) ;
1287 print "$orig_key\t-> $key\t-> $value\n" ;
1290 $filename = "tree" ;
1293 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1294 or die "Cannot open $filename: $!\n";
1296 # Add some key/value pairs to the file
1297 $h{'mouse'} = 'mickey' ;
1298 $h{'Wall'} = 'Larry' ;
1299 $h{'Walls'} = 'Brick' ;
1300 $h{'Smith'} = 'John' ;
1304 print "IN ORDER\n" ;
1305 for ($st = $x->seq($key, $value, R_FIRST) ;
1307 $st = $x->seq($key, $value, R_NEXT) )
1309 { print "$key -> $value\n" }
1311 print "\nPARTIAL MATCH\n" ;
1331 a -> mouse -> mickey
1335 DB_RECNO provides an interface to flat text files. Both variable and
1336 fixed length records are supported.
1338 In order to make RECNO more compatible with Perl, the array offset for
1339 all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
1341 As with normal Perl arrays, a RECNO array can be accessed using
1342 negative indexes. The index -1 refers to the last element of the array,
1343 -2 the second last, and so on. Attempting to access an element before
1344 the start of the array will raise a fatal run-time error.
1346 =head2 The 'bval' Option
1348 The operation of the bval option warrants some discussion. Here is the
1349 definition of bval from the Berkeley DB 1.85 recno manual page:
1351 The delimiting byte to be used to mark the end of a
1352 record for variable-length records, and the pad charac-
1353 ter for fixed-length records. If no value is speci-
1354 fied, newlines (``\n'') are used to mark the end of
1355 variable-length records and fixed-length records are
1358 The second sentence is wrong. In actual fact bval will only default to
1359 C<"\n"> when the openinfo parameter in dbopen is NULL. If a non-NULL
1360 openinfo parameter is used at all, the value that happens to be in bval
1361 will be used. That means you always have to specify bval when making
1362 use of any of the options in the openinfo parameter. This documentation
1363 error will be fixed in the next release of Berkeley DB.
1365 That clarifies the situation with regards Berkeley DB itself. What
1366 about B<DB_File>? Well, the behavior defined in the quote above is
1367 quite useful, so B<DB_File> conforms to it.
1369 That means that you can specify other options (e.g. cachesize) and
1370 still have bval default to C<"\n"> for variable length records, and
1371 space for fixed length records.
1373 Also note that the bval option only allows you to specify a single byte
1376 =head2 A Simple Example
1378 Here is a simple example that uses RECNO (if you are using a version
1379 of Perl earlier than 5.004_57 this example won't work -- see
1380 L<Extra RECNO Methods> for a workaround).
1386 my $filename = "text" ;
1390 tie @h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_RECNO
1391 or die "Cannot open file 'text': $!\n" ;
1393 # Add a few key/value pairs to the file
1398 push @h, "green", "black" ;
1400 my $elements = scalar @h ;
1401 print "The array contains $elements entries\n" ;
1404 print "popped $last\n" ;
1406 unshift @h, "white" ;
1407 my $first = shift @h ;
1408 print "shifted $first\n" ;
1410 # Check for existence of a key
1411 print "Element 1 Exists with value $h[1]\n" if $h[1] ;
1413 # use a negative index
1414 print "The last element is $h[-1]\n" ;
1415 print "The 2nd last element is $h[-2]\n" ;
1419 Here is the output from the script:
1421 The array contains 5 entries
1424 Element 1 Exists with value blue
1425 The last element is green
1426 The 2nd last element is yellow
1428 =head2 Extra RECNO Methods
1430 If you are using a version of Perl earlier than 5.004_57, the tied
1431 array interface is quite limited. In the example script above
1432 C<push>, C<pop>, C<shift>, C<unshift>
1433 or determining the array length will not work with a tied array.
1435 To make the interface more useful for older versions of Perl, a number
1436 of methods are supplied with B<DB_File> to simulate the missing array
1437 operations. All these methods are accessed via the object returned from
1440 Here are the methods:
1444 =item B<$X-E<gt>push(list) ;>
1446 Pushes the elements of C<list> to the end of the array.
1448 =item B<$value = $X-E<gt>pop ;>
1450 Removes and returns the last element of the array.
1452 =item B<$X-E<gt>shift>
1454 Removes and returns the first element of the array.
1456 =item B<$X-E<gt>unshift(list) ;>
1458 Pushes the elements of C<list> to the start of the array.
1460 =item B<$X-E<gt>length>
1462 Returns the number of elements in the array.
1464 =item B<$X-E<gt>splice(offset, length, elements);>
1466 Returns a splice of the array.
1470 =head2 Another Example
1472 Here is a more complete example that makes use of some of the methods
1473 described above. It also makes use of the API interface directly (see
1474 L<THE API INTERFACE>).
1478 my (@h, $H, $file, $i) ;
1486 $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0666, $DB_RECNO
1487 or die "Cannot open file $file: $!\n" ;
1489 # first create a text file to play with
1497 # Print the records in order.
1499 # The length method is needed here because evaluating a tied
1500 # array in a scalar context does not return the number of
1501 # elements in the array.
1503 print "\nORIGINAL\n" ;
1504 foreach $i (0 .. $H->length - 1) {
1505 print "$i: $h[$i]\n" ;
1508 # use the push & pop methods
1511 print "\nThe last record was [$a]\n" ;
1513 # and the shift & unshift methods
1515 $H->unshift("first") ;
1516 print "The first record was [$a]\n" ;
1518 # Use the API to add a new record after record 2.
1520 $H->put($i, "Newbie", R_IAFTER) ;
1522 # and a new record before record 1.
1524 $H->put($i, "New One", R_IBEFORE) ;
1529 # now print the records in reverse order
1530 print "\nREVERSE\n" ;
1531 for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
1532 { print "$i: $h[$i]\n" }
1534 # same again, but use the API functions instead
1535 print "\nREVERSE again\n" ;
1536 my ($s, $k, $v) = (0, 0, 0) ;
1537 for ($s = $H->seq($k, $v, R_LAST) ;
1539 $s = $H->seq($k, $v, R_PREV))
1540 { print "$k: $v\n" }
1545 and this is what it outputs:
1554 The last record was [four]
1555 The first record was [zero]
1579 Rather than iterating through the array, C<@h> like this:
1583 it is necessary to use either this:
1585 foreach $i (0 .. $H->length - 1)
1589 for ($a = $H->get($k, $v, R_FIRST) ;
1591 $a = $H->get($k, $v, R_NEXT) )
1595 Notice that both times the C<put> method was used the record index was
1596 specified using a variable, C<$i>, rather than the literal value
1597 itself. This is because C<put> will return the record number of the
1598 inserted line via that parameter.
1602 =head1 THE API INTERFACE
1604 As well as accessing Berkeley DB using a tied hash or array, it is also
1605 possible to make direct use of most of the API functions defined in the
1606 Berkeley DB documentation.
1608 To do this you need to store a copy of the object returned from the tie.
1610 $db = tie %hash, "DB_File", "filename" ;
1612 Once you have done that, you can access the Berkeley DB API functions
1613 as B<DB_File> methods directly like this:
1615 $db->put($key, $value, R_NOOVERWRITE) ;
1617 B<Important:> If you have saved a copy of the object returned from
1618 C<tie>, the underlying database file will I<not> be closed until both
1619 the tied variable is untied and all copies of the saved object are
1623 $db = tie %hash, "DB_File", "filename"
1624 or die "Cannot tie filename: $!" ;
1629 See L<The untie() Gotcha> for more details.
1631 All the functions defined in L<dbopen> are available except for
1632 close() and dbopen() itself. The B<DB_File> method interface to the
1633 supported functions have been implemented to mirror the way Berkeley DB
1634 works whenever possible. In particular note that:
1640 The methods return a status value. All return 0 on success.
1641 All return -1 to signify an error and set C<$!> to the exact
1642 error code. The return code 1 generally (but not always) means that the
1643 key specified did not exist in the database.
1645 Other return codes are defined. See below and in the Berkeley DB
1646 documentation for details. The Berkeley DB documentation should be used
1647 as the definitive source.
1651 Whenever a Berkeley DB function returns data via one of its parameters,
1652 the equivalent B<DB_File> method does exactly the same.
1656 If you are careful, it is possible to mix API calls with the tied
1657 hash/array interface in the same piece of code. Although only a few of
1658 the methods used to implement the tied interface currently make use of
1659 the cursor, you should always assume that the cursor has been changed
1660 any time the tied hash/array interface is used. As an example, this
1661 code will probably not do what you expect:
1663 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1664 or die "Cannot tie $filename: $!" ;
1666 # Get the first key/value pair and set the cursor
1667 $X->seq($key, $value, R_FIRST) ;
1669 # this line will modify the cursor
1670 $count = scalar keys %x ;
1672 # Get the second key/value pair.
1673 # oops, it didn't, it got the last key/value pair!
1674 $X->seq($key, $value, R_NEXT) ;
1676 The code above can be rearranged to get around the problem, like this:
1678 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1679 or die "Cannot tie $filename: $!" ;
1681 # this line will modify the cursor
1682 $count = scalar keys %x ;
1684 # Get the first key/value pair and set the cursor
1685 $X->seq($key, $value, R_FIRST) ;
1687 # Get the second key/value pair.
1689 $X->seq($key, $value, R_NEXT) ;
1693 All the constants defined in L<dbopen> for use in the flags parameters
1694 in the methods defined below are also available. Refer to the Berkeley
1695 DB documentation for the precise meaning of the flags values.
1697 Below is a list of the methods available.
1701 =item B<$status = $X-E<gt>get($key, $value [, $flags]) ;>
1703 Given a key (C<$key>) this method reads the value associated with it
1704 from the database. The value read from the database is returned in the
1705 C<$value> parameter.
1707 If the key does not exist the method returns 1.
1709 No flags are currently defined for this method.
1711 =item B<$status = $X-E<gt>put($key, $value [, $flags]) ;>
1713 Stores the key/value pair in the database.
1715 If you use either the R_IAFTER or R_IBEFORE flags, the C<$key> parameter
1716 will have the record number of the inserted key/value pair set.
1718 Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
1721 =item B<$status = $X-E<gt>del($key [, $flags]) ;>
1723 Removes all key/value pairs with key C<$key> from the database.
1725 A return code of 1 means that the requested key was not in the
1728 R_CURSOR is the only valid flag at present.
1730 =item B<$status = $X-E<gt>fd ;>
1732 Returns the file descriptor for the underlying database.
1734 See L<Locking: The Trouble with fd> for an explanation for why you should
1735 not use C<fd> to lock your database.
1737 =item B<$status = $X-E<gt>seq($key, $value, $flags) ;>
1739 This interface allows sequential retrieval from the database. See
1740 L<dbopen> for full details.
1742 Both the C<$key> and C<$value> parameters will be set to the key/value
1743 pair read from the database.
1745 The flags parameter is mandatory. The valid flag values are R_CURSOR,
1746 R_FIRST, R_LAST, R_NEXT and R_PREV.
1748 =item B<$status = $X-E<gt>sync([$flags]) ;>
1750 Flushes any cached buffers to disk.
1752 R_RECNOSYNC is the only valid flag at present.
1758 A DBM Filter is a piece of code that is be used when you I<always>
1759 want to make the same transformation to all keys and/or values in a
1762 There are four methods associated with DBM Filters. All work identically,
1763 and each is used to install (or uninstall) a single DBM Filter. Each
1764 expects a single parameter, namely a reference to a sub. The only
1765 difference between them is the place that the filter is installed.
1771 =item B<filter_store_key>
1773 If a filter has been installed with this method, it will be invoked
1774 every time you write a key to a DBM database.
1776 =item B<filter_store_value>
1778 If a filter has been installed with this method, it will be invoked
1779 every time you write a value to a DBM database.
1782 =item B<filter_fetch_key>
1784 If a filter has been installed with this method, it will be invoked
1785 every time you read a key from a DBM database.
1787 =item B<filter_fetch_value>
1789 If a filter has been installed with this method, it will be invoked
1790 every time you read a value from a DBM database.
1794 You can use any combination of the methods, from none, to all four.
1796 All filter methods return the existing filter, if present, or C<undef>
1799 To delete a filter pass C<undef> to it.
1803 When each filter is called by Perl, a local copy of C<$_> will contain
1804 the key or value to be filtered. Filtering is achieved by modifying
1805 the contents of C<$_>. The return code from the filter is ignored.
1807 =head2 An Example -- the NULL termination problem.
1809 Consider the following scenario. You have a DBM database
1810 that you need to share with a third-party C application. The C application
1811 assumes that I<all> keys and values are NULL terminated. Unfortunately
1812 when Perl writes to DBM databases it doesn't use NULL termination, so
1813 your Perl application will have to manage NULL termination itself. When
1814 you write to the database you will have to use something like this:
1816 $hash{"$key\0"} = "$value\0" ;
1818 Similarly the NULL needs to be taken into account when you are considering
1819 the length of existing keys/values.
1821 It would be much better if you could ignore the NULL terminations issue
1822 in the main application code and have a mechanism that automatically
1823 added the terminating NULL to all keys and values whenever you write to
1824 the database and have them removed when you read from the database. As I'm
1825 sure you have already guessed, this is a problem that DBM Filters can
1833 my $filename = "filt" ;
1836 my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
1837 or die "Cannot open $filename: $!\n" ;
1839 # Install DBM Filters
1840 $db->filter_fetch_key ( sub { s/\0$// } ) ;
1841 $db->filter_store_key ( sub { $_ .= "\0" } ) ;
1842 $db->filter_fetch_value( sub { s/\0$// } ) ;
1843 $db->filter_store_value( sub { $_ .= "\0" } ) ;
1845 $hash{"abc"} = "def" ;
1846 my $a = $hash{"ABC"} ;
1851 Hopefully the contents of each of the filters should be
1852 self-explanatory. Both "fetch" filters remove the terminating NULL,
1853 and both "store" filters add a terminating NULL.
1856 =head2 Another Example -- Key is a C int.
1858 Here is another real-life example. By default, whenever Perl writes to
1859 a DBM database it always writes the key and value as strings. So when
1862 $hash{12345} = "something" ;
1864 the key 12345 will get stored in the DBM database as the 5 byte string
1865 "12345". If you actually want the key to be stored in the DBM database
1866 as a C int, you will have to use C<pack> when writing, and C<unpack>
1869 Here is a DBM Filter that does it:
1875 my $filename = "filt" ;
1879 my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
1880 or die "Cannot open $filename: $!\n" ;
1882 $db->filter_fetch_key ( sub { $_ = unpack("i", $_) } ) ;
1883 $db->filter_store_key ( sub { $_ = pack ("i", $_) } ) ;
1884 $hash{123} = "def" ;
1889 This time only two filters have been used -- we only need to manipulate
1890 the contents of the key, so it wasn't necessary to install any value
1893 =head1 HINTS AND TIPS
1896 =head2 Locking: The Trouble with fd
1898 Until version 1.72 of this module, the recommended technique for locking
1899 B<DB_File> databases was to flock the filehandle returned from the "fd"
1900 function. Unfortunately this technique has been shown to be fundamentally
1901 flawed (Kudos to David Harris for tracking this down). Use it at your own
1904 The locking technique went like this.
1906 $db = tie(%db, 'DB_File', 'foo.db', O_CREAT|O_RDWR, 0644)
1907 || die "dbcreat foo.db $!";
1909 open(DB_FH, "+<&=$fd") || die "dup $!";
1910 flock (DB_FH, LOCK_EX) || die "flock: $!";
1912 $db{"Tom"} = "Jerry" ;
1914 flock(DB_FH, LOCK_UN);
1919 In simple terms, this is what happens:
1925 Use "tie" to open the database.
1929 Lock the database with fd & flock.
1933 Read & Write to the database.
1937 Unlock and close the database.
1941 Here is the crux of the problem. A side-effect of opening the B<DB_File>
1942 database in step 2 is that an initial block from the database will get
1943 read from disk and cached in memory.
1945 To see why this is a problem, consider what can happen when two processes,
1946 say "A" and "B", both want to update the same B<DB_File> database
1947 using the locking steps outlined above. Assume process "A" has already
1948 opened the database and has a write lock, but it hasn't actually updated
1949 the database yet (it has finished step 2, but not started step 3 yet). Now
1950 process "B" tries to open the same database - step 1 will succeed,
1951 but it will block on step 2 until process "A" releases the lock. The
1952 important thing to notice here is that at this point in time both
1953 processes will have cached identical initial blocks from the database.
1955 Now process "A" updates the database and happens to change some of the
1956 data held in the initial buffer. Process "A" terminates, flushing
1957 all cached data to disk and releasing the database lock. At this point
1958 the database on disk will correctly reflect the changes made by process
1961 With the lock released, process "B" can now continue. It also updates the
1962 database and unfortunately it too modifies the data that was in its
1963 initial buffer. Once that data gets flushed to disk it will overwrite
1964 some/all of the changes process "A" made to the database.
1966 The result of this scenario is at best a database that doesn't contain
1967 what you expect. At worst the database will corrupt.
1969 The above won't happen every time competing process update the same
1970 B<DB_File> database, but it does illustrate why the technique should
1973 =head2 Safe ways to lock a database
1975 Starting with version 2.x, Berkeley DB has internal support for locking.
1976 The companion module to this one, B<BerkeleyDB>, provides an interface
1977 to this locking functionality. If you are serious about locking
1978 Berkeley DB databases, I strongly recommend using B<BerkeleyDB>.
1980 If using B<BerkeleyDB> isn't an option, there are a number of modules
1981 available on CPAN that can be used to implement locking. Each one
1982 implements locking differently and has different goals in mind. It is
1983 therefore worth knowing the difference, so that you can pick the right
1984 one for your application. Here are the three locking wrappers:
1988 =item B<Tie::DB_Lock>
1990 A B<DB_File> wrapper which creates copies of the database file for
1991 read access, so that you have a kind of a multiversioning concurrent read
1992 system. However, updates are still serial. Use for databases where reads
1993 may be lengthy and consistency problems may occur.
1995 =item B<Tie::DB_LockFile>
1997 A B<DB_File> wrapper that has the ability to lock and unlock the database
1998 while it is being used. Avoids the tie-before-flock problem by simply
1999 re-tie-ing the database when you get or drop a lock. Because of the
2000 flexibility in dropping and re-acquiring the lock in the middle of a
2001 session, this can be massaged into a system that will work with long
2002 updates and/or reads if the application follows the hints in the POD
2005 =item B<DB_File::Lock>
2007 An extremely lightweight B<DB_File> wrapper that simply flocks a lockfile
2008 before tie-ing the database and drops the lock after the untie. Allows
2009 one to use the same lockfile for multiple databases to avoid deadlock
2010 problems, if desired. Use for databases where updates are reads are
2011 quick and simple flock locking semantics are enough.
2015 =head2 Sharing Databases With C Applications
2017 There is no technical reason why a Berkeley DB database cannot be
2018 shared by both a Perl and a C application.
2020 The vast majority of problems that are reported in this area boil down
2021 to the fact that C strings are NULL terminated, whilst Perl strings are
2022 not. See L<DBM FILTERS> for a generic way to work around this problem.
2024 Here is a real example. Netscape 2.0 keeps a record of the locations you
2025 visit along with the time you last visited them in a DB_HASH database.
2026 This is usually stored in the file F<~/.netscape/history.db>. The key
2027 field in the database is the location string and the value field is the
2028 time the location was last visited stored as a 4 byte binary value.
2030 If you haven't already guessed, the location string is stored with a
2031 terminating NULL. This means you need to be careful when accessing the
2034 Here is a snippet of code that is loosely based on Tom Christiansen's
2035 I<ggh> script (available from your nearest CPAN archive in
2036 F<authors/id/TOMC/scripts/nshist.gz>).
2043 my ($dotdir, $HISTORY, %hist_db, $href, $binary_time, $date) ;
2044 $dotdir = $ENV{HOME} || $ENV{LOGNAME};
2046 $HISTORY = "$dotdir/.netscape/history.db";
2048 tie %hist_db, 'DB_File', $HISTORY
2049 or die "Cannot open $HISTORY: $!\n" ;;
2051 # Dump the complete database
2052 while ( ($href, $binary_time) = each %hist_db ) {
2054 # remove the terminating NULL
2055 $href =~ s/\x00$// ;
2057 # convert the binary time into a user friendly string
2058 $date = localtime unpack("V", $binary_time);
2059 print "$date $href\n" ;
2062 # check for the existence of a specific key
2063 # remember to add the NULL
2064 if ( $binary_time = $hist_db{"http://mox.perl.com/\x00"} ) {
2065 $date = localtime unpack("V", $binary_time) ;
2066 print "Last visited mox.perl.com on $date\n" ;
2069 print "Never visited mox.perl.com\n"
2074 =head2 The untie() Gotcha
2076 If you make use of the Berkeley DB API, it is I<very> strongly
2077 recommended that you read L<perltie/The untie Gotcha>.
2079 Even if you don't currently make use of the API interface, it is still
2082 Here is an example which illustrates the problem from a B<DB_File>
2091 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
2092 or die "Cannot tie first time: $!" ;
2098 tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
2099 or die "Cannot tie second time: $!" ;
2103 When run, the script will produce this error message:
2105 Cannot tie second time: Invalid argument at bad.file line 14.
2107 Although the error message above refers to the second tie() statement
2108 in the script, the source of the problem is really with the untie()
2109 statement that precedes it.
2111 Having read L<perltie> you will probably have already guessed that the
2112 error is caused by the extra copy of the tied object stored in C<$X>.
2113 If you haven't, then the problem boils down to the fact that the
2114 B<DB_File> destructor, DESTROY, will not be called until I<all>
2115 references to the tied object are destroyed. Both the tied variable,
2116 C<%x>, and C<$X> above hold a reference to the object. The call to
2117 untie() will destroy the first, but C<$X> still holds a valid
2118 reference, so the destructor will not get called and the database file
2119 F<tst.fil> will remain open. The fact that Berkeley DB then reports the
2120 attempt to open a database that is already open via the catch-all
2121 "Invalid argument" doesn't help.
2123 If you run the script with the C<-w> flag the error message becomes:
2125 untie attempted while 1 inner references still exist at bad.file line 12.
2126 Cannot tie second time: Invalid argument at bad.file line 14.
2128 which pinpoints the real problem. Finally the script can now be
2129 modified to fix the original problem by destroying the API object
2138 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
2142 =head1 COMMON QUESTIONS
2144 =head2 Why is there Perl source in my database?
2146 If you look at the contents of a database file created by DB_File,
2147 there can sometimes be part of a Perl script included in it.
2149 This happens because Berkeley DB uses dynamic memory to allocate
2150 buffers which will subsequently be written to the database file. Being
2151 dynamic, the memory could have been used for anything before DB
2152 malloced it. As Berkeley DB doesn't clear the memory once it has been
2153 allocated, the unused portions will contain random junk. In the case
2154 where a Perl script gets written to the database, the random junk will
2155 correspond to an area of dynamic memory that happened to be used during
2156 the compilation of the script.
2158 Unless you don't like the possibility of there being part of your Perl
2159 scripts embedded in a database file, this is nothing to worry about.
2161 =head2 How do I store complex data structures with DB_File?
2163 Although B<DB_File> cannot do this directly, there is a module which
2164 can layer transparently over B<DB_File> to accomplish this feat.
2166 Check out the MLDBM module, available on CPAN in the directory
2167 F<modules/by-module/MLDBM>.
2169 =head2 What does "Invalid Argument" mean?
2171 You will get this error message when one of the parameters in the
2172 C<tie> call is wrong. Unfortunately there are quite a few parameters to
2173 get wrong, so it can be difficult to figure out which one it is.
2175 Here are a couple of possibilities:
2181 Attempting to reopen a database without closing it.
2185 Using the O_WRONLY flag.
2189 =head2 What does "Bareword 'DB_File' not allowed" mean?
2191 You will encounter this particular error message when you have the
2192 C<strict 'subs'> pragma (or the full strict pragma) in your script.
2193 Consider this script:
2199 tie %x, DB_File, "filename" ;
2201 Running it produces the error in question:
2203 Bareword "DB_File" not allowed while "strict subs" in use
2205 To get around the error, place the word C<DB_File> in either single or
2206 double quotes, like this:
2208 tie %x, "DB_File", "filename" ;
2210 Although it might seem like a real pain, it is really worth the effort
2211 of having a C<use strict> in all your scripts.
2215 Articles that are either about B<DB_File> or make use of it.
2221 I<Full-Text Searching in Perl>, Tim Kientzle (tkientzle@ddj.com),
2222 Dr. Dobb's Journal, Issue 295, January 1999, pp 34-41
2228 Moved to the Changes file.
2232 Some older versions of Berkeley DB had problems with fixed length
2233 records using the RECNO file format. This problem has been fixed since
2234 version 1.85 of Berkeley DB.
2236 I am sure there are bugs in the code. If you do find any, or can
2237 suggest any enhancements, I would welcome your comments.
2241 B<DB_File> comes with the standard Perl source distribution. Look in
2242 the directory F<ext/DB_File>. Given the amount of time between releases
2243 of Perl the version that ships with Perl is quite likely to be out of
2244 date, so the most recent version can always be found on CPAN (see
2245 L<perlmodlib/CPAN> for details), in the directory
2246 F<modules/by-module/DB_File>.
2248 This version of B<DB_File> will work with either version 1.x, 2.x or
2249 3.x of Berkeley DB, but is limited to the functionality provided by
2252 The official web site for Berkeley DB is F<http://www.oracle.com/technology/products/berkeley-db/db/index.html>.
2253 All versions of Berkeley DB are available there.
2255 Alternatively, Berkeley DB version 1 is available at your nearest CPAN
2256 archive in F<src/misc/db.1.85.tar.gz>.
2258 If you are running IRIX, then get Berkeley DB version 1 from
2259 F<http://reality.sgi.com/ariel>. It has the patches necessary to
2260 compile properly on IRIX 5.3.
2264 Copyright (c) 1995-2007 Paul Marquess. All rights reserved. This program
2265 is free software; you can redistribute it and/or modify it under the
2266 same terms as Perl itself.
2268 Although B<DB_File> is covered by the Perl license, the library it
2269 makes use of, namely Berkeley DB, is not. Berkeley DB has its own
2270 copyright and its own license. Please take the time to read it.
2272 Here are are few words taken from the Berkeley DB FAQ (at
2273 F<http://www.oracle.com/technology/products/berkeley-db/db/index.html>) regarding the license:
2275 Do I have to license DB to use it in Perl scripts?
2277 No. The Berkeley DB license requires that software that uses
2278 Berkeley DB be freely redistributable. In the case of Perl, that
2279 software is Perl, and not your scripts. Any Perl scripts that you
2280 write are your property, including scripts that make use of
2281 Berkeley DB. Neither the Perl license nor the Berkeley DB license
2282 place any restriction on what you may do with them.
2284 If you are in any doubt about the license situation, contact either the
2285 Berkeley DB authors or the author of DB_File. See L<"AUTHOR"> for details.
2290 L<perl>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>,
2295 The DB_File interface was written by Paul Marquess
2296 E<lt>pmqs@cpan.orgE<gt>.