1 # DB_File.pm -- Perl 5 interface to Berkeley DB
3 # Written by Paul Marquess (pmqs@cpan.org)
5 # Copyright (c) 1995-2013 Paul Marquess. All rights reserved.
6 # This program is free software; you can redistribute it and/or
7 # modify it under the same terms as Perl itself.
10 package DB_File::HASHINFO ;
18 @DB_File::HASHINFO::ISA = qw(Tie::Hash);
51 return $self->{GOT}{$key} if exists $self->{VALID}{$key} ;
54 croak "${pkg}::FETCH - Unknown element '$key'" ;
64 my $type = $self->{VALID}{$key};
68 croak "Key '$key' not associated with a code reference"
69 if $type == 2 && !ref $value && ref $value ne 'CODE';
70 $self->{GOT}{$key} = $value ;
75 croak "${pkg}::STORE - Unknown element '$key'" ;
83 if ( exists $self->{VALID}{$key} )
85 delete $self->{GOT}{$key} ;
90 croak "DB_File::HASHINFO::DELETE - Unknown element '$key'" ;
98 exists $self->{VALID}{$key} ;
106 croak ref($self) . " does not define the method ${method}" ;
109 sub FIRSTKEY { my $self = shift ; $self->NotHere("FIRSTKEY") }
110 sub NEXTKEY { my $self = shift ; $self->NotHere("NEXTKEY") }
111 sub CLEAR { my $self = shift ; $self->NotHere("CLEAR") }
113 package DB_File::RECNOINFO ;
118 @DB_File::RECNOINFO::ISA = qw(DB_File::HASHINFO) ;
124 bless { VALID => { map {$_, 1}
125 qw( bval cachesize psize flags lorder reclen bfname )
131 package DB_File::BTREEINFO ;
136 @DB_File::BTREEINFO::ISA = qw(DB_File::HASHINFO) ;
161 our ($VERSION, @ISA, @EXPORT, $AUTOLOAD, $DB_BTREE, $DB_HASH, $DB_RECNO);
162 our ($db_version, $use_XSLoader, $splice_end_array_no_length, $splice_end_array, $Error);
167 $VERSION = eval $VERSION; # needed for dev releases
170 local $SIG{__WARN__} = sub {$splice_end_array_no_length = join(" ",@_);};
171 my @a =(1); splice(@a, 3);
172 $splice_end_array_no_length =
173 ($splice_end_array_no_length =~ /^splice\(\) offset past end of array at /);
176 local $SIG{__WARN__} = sub {$splice_end_array = join(" ", @_);};
177 my @a =(1); splice(@a, 3, 1);
179 ($splice_end_array =~ /^splice\(\) offset past end of array at /);
182 #typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
183 $DB_BTREE = new DB_File::BTREEINFO ;
184 $DB_HASH = new DB_File::HASHINFO ;
185 $DB_RECNO = new DB_File::RECNOINFO ;
191 { local $SIG{__DIE__} ; eval { require XSLoader } ; }
196 @ISA = qw(DynaLoader);
200 push @ISA, qw(Tie::Hash Exporter);
202 $DB_BTREE $DB_HASH $DB_RECNO
237 ($constname = $AUTOLOAD) =~ s/.*:://;
238 my ($error, $val) = constant($constname);
239 Carp::croak $error if $error;
241 *{$AUTOLOAD} = sub { $val };
247 # Make all Fcntl O_XXX constants available for importing
249 my @O = grep /^O_/, @Fcntl::EXPORT;
250 Fcntl->import(@O); # first we import what we want to export
255 { XSLoader::load("DB_File", $VERSION)}
257 { bootstrap DB_File $VERSION }
259 sub tie_hash_or_array
262 my $tieHASH = ( (caller(1))[3] =~ /TIEHASH/ ) ;
265 $arg[1] = File::Spec->rel2abs($arg[1])
268 $arg[4] = tied %{ $arg[4] }
269 if @arg >= 5 && ref $arg[4] && $arg[4] =~ /=HASH/ && tied %{ $arg[4] } ;
271 $arg[2] = O_CREAT()|O_RDWR() if @arg >=3 && ! defined $arg[2];
272 $arg[3] = 0666 if @arg >=4 && ! defined $arg[3];
274 # make recno in Berkeley DB version 2 (or better) work like
275 # recno in version 1.
276 if ($db_version >= 4 and ! $tieHASH) {
277 $arg[2] |= O_CREAT();
280 if ($db_version > 1 and defined $arg[4] and $arg[4] =~ /RECNO/ and
281 $arg[1] and ! -e $arg[1]) {
282 open(FH, ">$arg[1]") or return undef ;
284 chmod $arg[3] ? $arg[3] : 0666 , $arg[1] ;
287 DoTie_($tieHASH, @arg) ;
292 tie_hash_or_array(@_) ;
297 tie_hash_or_array(@_) ;
305 my $status = $self->seq($key, $value, R_FIRST());
308 while ($status == 0) {
310 $status = $self->seq($key, $value, R_NEXT());
312 foreach $key (reverse @keys) {
313 my $s = $self->del($key);
323 my $current_length = $self->length() ;
325 if ($length < $current_length) {
327 for ($key = $current_length - 1 ; $key >= $length ; -- $key)
330 elsif ($length > $current_length) {
331 $self->put($length-1, "") ;
340 if (not defined $offset) {
341 warnings::warnif('uninitialized', 'Use of uninitialized value in splice');
346 my $length = @_ ? shift : 0;
347 # Carping about definedness comes _after_ the OFFSET sanity check.
348 # This is so we get the same error messages as Perl's splice().
353 my $size = $self->FETCHSIZE();
355 # 'If OFFSET is negative then it start that far from the end of
359 my $new_offset = $size + $offset;
360 if ($new_offset < 0) {
361 die "Modification of non-creatable array value attempted, "
362 . "subscript $offset";
364 $offset = $new_offset;
367 if (not defined $length) {
368 warnings::warnif('uninitialized', 'Use of uninitialized value in splice');
372 if ($offset > $size) {
374 warnings::warnif('misc', 'splice() offset past end of array')
375 if $has_length ? $splice_end_array : $splice_end_array_no_length;
378 # 'If LENGTH is omitted, removes everything from OFFSET onward.'
379 if (not defined $length) {
380 $length = $size - $offset;
383 # 'If LENGTH is negative, leave that many elements off the end of
387 $length = $size - $offset + $length;
390 # The user must have specified a length bigger than the
391 # length of the array passed in. But perl's splice()
392 # doesn't catch this, it just behaves as for length=0.
398 if ($length > $size - $offset) {
399 $length = $size - $offset;
402 # $num_elems holds the current number of elements in the database.
403 my $num_elems = $size;
405 # 'Removes the elements designated by OFFSET and LENGTH from an
409 foreach (0 .. $length - 1) {
411 my $status = $self->get($offset, $old);
413 my $msg = "error from Berkeley DB on get($offset, \$old)";
415 $msg .= ' (no such element?)';
418 $msg .= ": error status $status";
419 if (defined $! and $! ne '') {
420 $msg .= ", message $!";
427 $status = $self->del($offset);
429 my $msg = "error from Berkeley DB on del($offset)";
431 $msg .= ' (no such element?)';
434 $msg .= ": error status $status";
435 if (defined $! and $! ne '') {
436 $msg .= ", message $!";
445 # ...'and replaces them with the elements of LIST, if any.'
447 while (defined (my $elem = shift @list)) {
450 if ($pos >= $num_elems) {
451 $status = $self->put($pos, $elem);
454 $status = $self->put($pos, $elem, $self->R_IBEFORE);
458 my $msg = "error from Berkeley DB on put($pos, $elem, ...)";
460 $msg .= ' (no such element?)';
463 $msg .= ", error status $status";
464 if (defined $! and $! ne '') {
465 $msg .= ", message $!";
471 die "pos unexpectedly changed from $old_pos to $pos with R_IBEFORE"
479 # 'In list context, returns the elements removed from the
484 elsif (defined wantarray and not wantarray) {
485 # 'In scalar context, returns the last element removed, or
486 # undef if no elements are removed.'
489 my $last = pop @removed;
496 elsif (not defined wantarray) {
501 sub ::DB_File::splice { &SPLICE }
505 croak "Usage: \$db->find_dup(key,value)\n"
509 my ($origkey, $value_wanted) = @_ ;
510 my ($key, $value) = ($origkey, 0);
513 for ($status = $db->seq($key, $value, R_CURSOR() ) ;
515 $status = $db->seq($key, $value, R_NEXT() ) ) {
517 return 0 if $key eq $origkey and $value eq $value_wanted ;
525 croak "Usage: \$db->del_dup(key,value)\n"
529 my ($key, $value) = @_ ;
530 my ($status) = $db->find_dup($key, $value) ;
531 return $status if $status != 0 ;
533 $status = $db->del($key, R_CURSOR() ) ;
539 croak "Usage: \$db->get_dup(key [,flag])\n"
540 unless @_ == 2 or @_ == 3 ;
547 my $wantarray = wantarray ;
553 # iterate through the database until either EOF ($status == 0)
554 # or a different key is encountered ($key ne $origkey).
555 for ($status = $db->seq($key, $value, R_CURSOR()) ;
556 $status == 0 and $key eq $origkey ;
557 $status = $db->seq($key, $value, R_NEXT()) ) {
559 # save the value or count number of matches
562 { ++ $values{$value} }
564 { push (@values, $value) }
571 return ($wantarray ? ($flag ? %values : @values) : $counter) ;
577 my $type = ref shift;
578 croak "Cannot freeze $type object\n";
583 my $type = ref shift;
584 croak "Cannot thaw $type object\n";
594 DB_File - Perl5 access to Berkeley DB version 1.x
600 [$X =] tie %hash, 'DB_File', [$filename, $flags, $mode, $DB_HASH] ;
601 [$X =] tie %hash, 'DB_File', $filename, $flags, $mode, $DB_BTREE ;
602 [$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ;
604 $status = $X->del($key [, $flags]) ;
605 $status = $X->put($key, $value [, $flags]) ;
606 $status = $X->get($key, $value [, $flags]) ;
607 $status = $X->seq($key, $value, $flags) ;
608 $status = $X->sync([$flags]) ;
612 $count = $X->get_dup($key) ;
613 @list = $X->get_dup($key) ;
614 %list = $X->get_dup($key, 1) ;
615 $status = $X->find_dup($key, $value) ;
616 $status = $X->del_dup($key, $value) ;
624 @r = $X->splice(offset, length, elements);
627 $old_filter = $db->filter_store_key ( sub { ... } ) ;
628 $old_filter = $db->filter_store_value( sub { ... } ) ;
629 $old_filter = $db->filter_fetch_key ( sub { ... } ) ;
630 $old_filter = $db->filter_fetch_value( sub { ... } ) ;
637 B<DB_File> is a module which allows Perl programs to make use of the
638 facilities provided by Berkeley DB version 1.x (if you have a newer
639 version of DB, see L<Using DB_File with Berkeley DB version 2 or greater>).
640 It is assumed that you have a copy of the Berkeley DB manual pages at
641 hand when reading this documentation. The interface defined here
642 mirrors the Berkeley DB interface closely.
644 Berkeley DB is a C library which provides a consistent interface to a
645 number of database formats. B<DB_File> provides an interface to all
646 three of the database types currently supported by Berkeley DB.
654 This database type allows arbitrary key/value pairs to be stored in data
655 files. This is equivalent to the functionality provided by other
656 hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
657 the files created using DB_HASH are not compatible with any of the
658 other packages mentioned.
660 A default hashing algorithm, which will be adequate for most
661 applications, is built into Berkeley DB. If you do need to use your own
662 hashing algorithm it is possible to write your own in Perl and have
663 B<DB_File> use it instead.
667 The btree format allows arbitrary key/value pairs to be stored in a
668 sorted, balanced binary tree.
670 As with the DB_HASH format, it is possible to provide a user defined
671 Perl routine to perform the comparison of keys. By default, though, the
672 keys are stored in lexical order.
676 DB_RECNO allows both fixed-length and variable-length flat text files
677 to be manipulated using the same key/value pair interface as in DB_HASH
678 and DB_BTREE. In this case the key will consist of a record (line)
683 =head2 Using DB_File with Berkeley DB version 2 or greater
685 Although B<DB_File> is intended to be used with Berkeley DB version 1,
686 it can also be used with version 2, 3 or 4. In this case the interface is
687 limited to the functionality provided by Berkeley DB 1.x. Anywhere the
688 version 2 or greater interface differs, B<DB_File> arranges for it to work
689 like version 1. This feature allows B<DB_File> scripts that were built
690 with version 1 to be migrated to version 2 or greater without any changes.
692 If you want to make use of the new features available in Berkeley DB
693 2.x or greater, use the Perl module B<BerkeleyDB> instead.
695 B<Note:> The database file format has changed multiple times in Berkeley
696 DB version 2, 3 and 4. If you cannot recreate your databases, you
697 must dump any existing databases with either the C<db_dump> or the
698 C<db_dump185> utility that comes with Berkeley DB.
699 Once you have rebuilt DB_File to use Berkeley DB version 2 or greater,
700 your databases can be recreated using C<db_load>. Refer to the Berkeley DB
701 documentation for further details.
703 Please read L<"COPYRIGHT"> before using version 2.x or greater of Berkeley
706 =head2 Interface to Berkeley DB
708 B<DB_File> allows access to Berkeley DB files using the tie() mechanism
709 in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
710 allows B<DB_File> to access Berkeley DB files using either an
711 associative array (for DB_HASH & DB_BTREE file types) or an ordinary
712 array (for the DB_RECNO file type).
714 In addition to the tie() interface, it is also possible to access most
715 of the functions provided in the Berkeley DB API directly.
716 See L<THE API INTERFACE>.
718 =head2 Opening a Berkeley DB Database File
720 Berkeley DB uses the function dbopen() to open or create a database.
721 Here is the C prototype for dbopen():
724 dbopen (const char * file, int flags, int mode,
725 DBTYPE type, const void * openinfo)
727 The parameter C<type> is an enumeration which specifies which of the 3
728 interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
729 Depending on which of these is actually chosen, the final parameter,
730 I<openinfo> points to a data structure which allows tailoring of the
731 specific interface method.
733 This interface is handled slightly differently in B<DB_File>. Here is
734 an equivalent call using B<DB_File>:
736 tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
738 The C<filename>, C<flags> and C<mode> parameters are the direct
739 equivalent of their dbopen() counterparts. The final parameter $DB_HASH
740 performs the function of both the C<type> and C<openinfo> parameters in
743 In the example above $DB_HASH is actually a pre-defined reference to a
744 hash object. B<DB_File> has three of these pre-defined references.
745 Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
747 The keys allowed in each of these pre-defined references is limited to
748 the names used in the equivalent C structure. So, for example, the
749 $DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
750 C<ffactor>, C<hash>, C<lorder> and C<nelem>.
752 To change one of these elements, just assign to it like this:
754 $DB_HASH->{'cachesize'} = 10000 ;
756 The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
757 usually adequate for most applications. If you do need to create extra
758 instances of these objects, constructors are available for each file
761 Here are examples of the constructors and the valid options available
762 for DB_HASH, DB_BTREE and DB_RECNO respectively.
764 $a = new DB_File::HASHINFO ;
772 $b = new DB_File::BTREEINFO ;
782 $c = new DB_File::RECNOINFO ;
791 The values stored in the hashes above are mostly the direct equivalent
792 of their C counterpart. Like their C counterparts, all are set to a
793 default values - that means you don't have to set I<all> of the
794 values when you only want to change one. Here is an example:
796 $a = new DB_File::HASHINFO ;
797 $a->{'cachesize'} = 12345 ;
798 tie %y, 'DB_File', "filename", $flags, 0777, $a ;
800 A few of the options need extra discussion here. When used, the C
801 equivalent of the keys C<hash>, C<compare> and C<prefix> store pointers
802 to C functions. In B<DB_File> these keys are used to store references
803 to Perl subs. Below are templates for each of the subs:
809 # return the hash value for $data
815 my ($key, $key2) = @_ ;
817 # return 0 if $key1 eq $key2
818 # -1 if $key1 lt $key2
819 # 1 if $key1 gt $key2
820 return (-1 , 0 or 1) ;
825 my ($key, $key2) = @_ ;
827 # return number of bytes of $key2 which are
828 # necessary to determine that it is greater than $key1
832 See L<Changing the BTREE sort order> for an example of using the
835 If you are using the DB_RECNO interface and you intend making use of
836 C<bval>, you should check out L<The 'bval' Option>.
838 =head2 Default Parameters
840 It is possible to omit some or all of the final 4 parameters in the
841 call to C<tie> and let them take default values. As DB_HASH is the most
842 common file format used, the call:
844 tie %A, "DB_File", "filename" ;
848 tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
850 It is also possible to omit the filename parameter as well, so the
857 tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
859 See L<In Memory Databases> for a discussion on the use of C<undef>
860 in place of a filename.
862 =head2 In Memory Databases
864 Berkeley DB allows the creation of in-memory databases by using NULL
865 (that is, a C<(char *)0> in C) in place of the filename. B<DB_File>
866 uses C<undef> instead of NULL to provide this functionality.
870 The DB_HASH file format is probably the most commonly used of the three
871 file formats that B<DB_File> supports. It is also very straightforward
874 =head2 A Simple Example
876 This example shows how to create a database, add key/value pairs to the
877 database, delete keys/value pairs and finally how to enumerate the
878 contents of the database.
886 tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0666, $DB_HASH
887 or die "Cannot open file 'fruit': $!\n";
889 # Add a few key/value pairs to the file
890 $h{"apple"} = "red" ;
891 $h{"orange"} = "orange" ;
892 $h{"banana"} = "yellow" ;
893 $h{"tomato"} = "red" ;
895 # Check for existence of a key
896 print "Banana Exists\n\n" if $h{"banana"} ;
898 # Delete a key/value pair.
901 # print the contents of the file
902 while (($k, $v) = each %h)
903 { print "$k -> $v\n" }
915 Note that the like ordinary associative arrays, the order of the keys
916 retrieved is in an apparently random order.
920 The DB_BTREE format is useful when you want to store data in a given
921 order. By default the keys will be stored in lexical order, but as you
922 will see from the example shown in the next section, it is very easy to
923 define your own sorting function.
925 =head2 Changing the BTREE sort order
927 This script shows how to override the default sorting algorithm that
928 BTREE uses. Instead of using the normal lexical ordering, a case
929 insensitive compare function will be used.
939 my ($key1, $key2) = @_ ;
940 "\L$key1" cmp "\L$key2" ;
943 # specify the Perl sub that will do the comparison
944 $DB_BTREE->{'compare'} = \&Compare ;
947 tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0666, $DB_BTREE
948 or die "Cannot open file 'tree': $!\n" ;
950 # Add a key/value pair to the file
951 $h{'Wall'} = 'Larry' ;
952 $h{'Smith'} = 'John' ;
953 $h{'mouse'} = 'mickey' ;
954 $h{'duck'} = 'donald' ;
959 # Cycle through the keys printing them in order.
960 # Note it is not necessary to sort the keys as
961 # the btree will have kept them in order automatically.
967 Here is the output from the code above.
973 There are a few point to bear in mind if you want to change the
974 ordering in a BTREE database:
980 The new compare function must be specified when you create the database.
984 You cannot change the ordering once the database has been created. Thus
985 you must use the same compare function every time you access the
990 Duplicate keys are entirely defined by the comparison function.
991 In the case-insensitive example above, the keys: 'KEY' and 'key'
992 would be considered duplicates, and assigning to the second one
993 would overwrite the first. If duplicates are allowed for (with the
994 R_DUP flag discussed below), only a single copy of duplicate keys
995 is stored in the database --- so (again with example above) assigning
996 three values to the keys: 'KEY', 'Key', and 'key' would leave just
997 the first key: 'KEY' in the database with three values. For some
998 situations this results in information loss, so care should be taken
999 to provide fully qualified comparison functions when necessary.
1000 For example, the above comparison routine could be modified to
1001 additionally compare case-sensitively if two keys are equal in the
1002 case insensitive comparison:
1005 my($key1, $key2) = @_;
1006 lc $key1 cmp lc $key2 ||
1010 And now you will only have duplicates when the keys themselves
1011 are truly the same. (note: in versions of the db library prior to
1012 about November 1996, such duplicate keys were retained so it was
1013 possible to recover the original keys in sets of keys that
1019 =head2 Handling Duplicate Keys
1021 The BTREE file type optionally allows a single key to be associated
1022 with an arbitrary number of values. This option is enabled by setting
1023 the flags element of C<$DB_BTREE> to R_DUP when creating the database.
1025 There are some difficulties in using the tied hash interface if you
1026 want to manipulate a BTREE database with duplicate keys. Consider this
1033 my ($filename, %h) ;
1035 $filename = "tree" ;
1038 # Enable duplicate records
1039 $DB_BTREE->{'flags'} = R_DUP ;
1041 tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1042 or die "Cannot open $filename: $!\n";
1044 # Add some key/value pairs to the file
1045 $h{'Wall'} = 'Larry' ;
1046 $h{'Wall'} = 'Brick' ; # Note the duplicate key
1047 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
1048 $h{'Smith'} = 'John' ;
1049 $h{'mouse'} = 'mickey' ;
1051 # iterate through the associative array
1052 # and print each key/value pair.
1053 foreach (sort keys %h)
1054 { print "$_ -> $h{$_}\n" }
1066 As you can see 3 records have been successfully created with key C<Wall>
1067 - the only thing is, when they are retrieved from the database they
1068 I<seem> to have the same value, namely C<Larry>. The problem is caused
1069 by the way that the associative array interface works. Basically, when
1070 the associative array interface is used to fetch the value associated
1071 with a given key, it will only ever retrieve the first value.
1073 Although it may not be immediately obvious from the code above, the
1074 associative array interface can be used to write values with duplicate
1075 keys, but it cannot be used to read them back from the database.
1077 The way to get around this problem is to use the Berkeley DB API method
1078 called C<seq>. This method allows sequential access to key/value
1079 pairs. See L<THE API INTERFACE> for details of both the C<seq> method
1080 and the API in general.
1082 Here is the script above rewritten using the C<seq> API method.
1088 my ($filename, $x, %h, $status, $key, $value) ;
1090 $filename = "tree" ;
1093 # Enable duplicate records
1094 $DB_BTREE->{'flags'} = R_DUP ;
1096 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1097 or die "Cannot open $filename: $!\n";
1099 # Add some key/value pairs to the file
1100 $h{'Wall'} = 'Larry' ;
1101 $h{'Wall'} = 'Brick' ; # Note the duplicate key
1102 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
1103 $h{'Smith'} = 'John' ;
1104 $h{'mouse'} = 'mickey' ;
1106 # iterate through the btree using seq
1107 # and print each key/value pair.
1109 for ($status = $x->seq($key, $value, R_FIRST) ;
1111 $status = $x->seq($key, $value, R_NEXT) )
1112 { print "$key -> $value\n" }
1125 This time we have got all the key/value pairs, including the multiple
1126 values associated with the key C<Wall>.
1128 To make life easier when dealing with duplicate keys, B<DB_File> comes with
1129 a few utility methods.
1131 =head2 The get_dup() Method
1133 The C<get_dup> method assists in
1134 reading duplicate values from BTREE databases. The method can take the
1137 $count = $x->get_dup($key) ;
1138 @list = $x->get_dup($key) ;
1139 %list = $x->get_dup($key, 1) ;
1141 In a scalar context the method returns the number of values associated
1142 with the key, C<$key>.
1144 In list context, it returns all the values which match C<$key>. Note
1145 that the values will be returned in an apparently random order.
1147 In list context, if the second parameter is present and evaluates
1148 TRUE, the method returns an associative array. The keys of the
1149 associative array correspond to the values that matched in the BTREE
1150 and the values of the array are a count of the number of times that
1151 particular value occurred in the BTREE.
1153 So assuming the database created above, we can use C<get_dup> like
1160 my ($filename, $x, %h) ;
1162 $filename = "tree" ;
1164 # Enable duplicate records
1165 $DB_BTREE->{'flags'} = R_DUP ;
1167 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1168 or die "Cannot open $filename: $!\n";
1170 my $cnt = $x->get_dup("Wall") ;
1171 print "Wall occurred $cnt times\n" ;
1173 my %hash = $x->get_dup("Wall", 1) ;
1174 print "Larry is there\n" if $hash{'Larry'} ;
1175 print "There are $hash{'Brick'} Brick Walls\n" ;
1177 my @list = sort $x->get_dup("Wall") ;
1178 print "Wall => [@list]\n" ;
1180 @list = $x->get_dup("Smith") ;
1181 print "Smith => [@list]\n" ;
1183 @list = $x->get_dup("Dog") ;
1184 print "Dog => [@list]\n" ;
1189 Wall occurred 3 times
1191 There are 2 Brick Walls
1192 Wall => [Brick Brick Larry]
1196 =head2 The find_dup() Method
1198 $status = $X->find_dup($key, $value) ;
1200 This method checks for the existence of a specific key/value pair. If the
1201 pair exists, the cursor is left pointing to the pair and the method
1202 returns 0. Otherwise the method returns a non-zero value.
1204 Assuming the database from the previous example:
1210 my ($filename, $x, %h, $found) ;
1212 $filename = "tree" ;
1214 # Enable duplicate records
1215 $DB_BTREE->{'flags'} = R_DUP ;
1217 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1218 or die "Cannot open $filename: $!\n";
1220 $found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
1221 print "Larry Wall is $found there\n" ;
1223 $found = ( $x->find_dup("Wall", "Harry") == 0 ? "" : "not") ;
1224 print "Harry Wall is $found there\n" ;
1232 Harry Wall is not there
1235 =head2 The del_dup() Method
1237 $status = $X->del_dup($key, $value) ;
1239 This method deletes a specific key/value pair. It returns
1240 0 if they exist and have been deleted successfully.
1241 Otherwise the method returns a non-zero value.
1243 Again assuming the existence of the C<tree> database
1249 my ($filename, $x, %h, $found) ;
1251 $filename = "tree" ;
1253 # Enable duplicate records
1254 $DB_BTREE->{'flags'} = R_DUP ;
1256 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1257 or die "Cannot open $filename: $!\n";
1259 $x->del_dup("Wall", "Larry") ;
1261 $found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
1262 print "Larry Wall is $found there\n" ;
1269 Larry Wall is not there
1271 =head2 Matching Partial Keys
1273 The BTREE interface has a feature which allows partial keys to be
1274 matched. This functionality is I<only> available when the C<seq> method
1275 is used along with the R_CURSOR flag.
1277 $x->seq($key, $value, R_CURSOR) ;
1279 Here is the relevant quote from the dbopen man page where it defines
1280 the use of the R_CURSOR flag with seq:
1282 Note, for the DB_BTREE access method, the returned key is not
1283 necessarily an exact match for the specified key. The returned key
1284 is the smallest key greater than or equal to the specified key,
1285 permitting partial key matches and range searches.
1287 In the example script below, the C<match> sub uses this feature to find
1288 and print the first matching key/value pair given a partial key.
1295 my ($filename, $x, %h, $st, $key, $value) ;
1301 my $orig_key = $key ;
1302 $x->seq($key, $value, R_CURSOR) ;
1303 print "$orig_key\t-> $key\t-> $value\n" ;
1306 $filename = "tree" ;
1309 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
1310 or die "Cannot open $filename: $!\n";
1312 # Add some key/value pairs to the file
1313 $h{'mouse'} = 'mickey' ;
1314 $h{'Wall'} = 'Larry' ;
1315 $h{'Walls'} = 'Brick' ;
1316 $h{'Smith'} = 'John' ;
1320 print "IN ORDER\n" ;
1321 for ($st = $x->seq($key, $value, R_FIRST) ;
1323 $st = $x->seq($key, $value, R_NEXT) )
1325 { print "$key -> $value\n" }
1327 print "\nPARTIAL MATCH\n" ;
1347 a -> mouse -> mickey
1351 DB_RECNO provides an interface to flat text files. Both variable and
1352 fixed length records are supported.
1354 In order to make RECNO more compatible with Perl, the array offset for
1355 all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
1357 As with normal Perl arrays, a RECNO array can be accessed using
1358 negative indexes. The index -1 refers to the last element of the array,
1359 -2 the second last, and so on. Attempting to access an element before
1360 the start of the array will raise a fatal run-time error.
1362 =head2 The 'bval' Option
1364 The operation of the bval option warrants some discussion. Here is the
1365 definition of bval from the Berkeley DB 1.85 recno manual page:
1367 The delimiting byte to be used to mark the end of a
1368 record for variable-length records, and the pad charac-
1369 ter for fixed-length records. If no value is speci-
1370 fied, newlines (``\n'') are used to mark the end of
1371 variable-length records and fixed-length records are
1374 The second sentence is wrong. In actual fact bval will only default to
1375 C<"\n"> when the openinfo parameter in dbopen is NULL. If a non-NULL
1376 openinfo parameter is used at all, the value that happens to be in bval
1377 will be used. That means you always have to specify bval when making
1378 use of any of the options in the openinfo parameter. This documentation
1379 error will be fixed in the next release of Berkeley DB.
1381 That clarifies the situation with regards Berkeley DB itself. What
1382 about B<DB_File>? Well, the behavior defined in the quote above is
1383 quite useful, so B<DB_File> conforms to it.
1385 That means that you can specify other options (e.g. cachesize) and
1386 still have bval default to C<"\n"> for variable length records, and
1387 space for fixed length records.
1389 Also note that the bval option only allows you to specify a single byte
1392 =head2 A Simple Example
1394 Here is a simple example that uses RECNO (if you are using a version
1395 of Perl earlier than 5.004_57 this example won't work -- see
1396 L<Extra RECNO Methods> for a workaround).
1402 my $filename = "text" ;
1406 tie @h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_RECNO
1407 or die "Cannot open file 'text': $!\n" ;
1409 # Add a few key/value pairs to the file
1414 push @h, "green", "black" ;
1416 my $elements = scalar @h ;
1417 print "The array contains $elements entries\n" ;
1420 print "popped $last\n" ;
1422 unshift @h, "white" ;
1423 my $first = shift @h ;
1424 print "shifted $first\n" ;
1426 # Check for existence of a key
1427 print "Element 1 Exists with value $h[1]\n" if $h[1] ;
1429 # use a negative index
1430 print "The last element is $h[-1]\n" ;
1431 print "The 2nd last element is $h[-2]\n" ;
1435 Here is the output from the script:
1437 The array contains 5 entries
1440 Element 1 Exists with value blue
1441 The last element is green
1442 The 2nd last element is yellow
1444 =head2 Extra RECNO Methods
1446 If you are using a version of Perl earlier than 5.004_57, the tied
1447 array interface is quite limited. In the example script above
1448 C<push>, C<pop>, C<shift>, C<unshift>
1449 or determining the array length will not work with a tied array.
1451 To make the interface more useful for older versions of Perl, a number
1452 of methods are supplied with B<DB_File> to simulate the missing array
1453 operations. All these methods are accessed via the object returned from
1456 Here are the methods:
1460 =item B<$X-E<gt>push(list) ;>
1462 Pushes the elements of C<list> to the end of the array.
1464 =item B<$value = $X-E<gt>pop ;>
1466 Removes and returns the last element of the array.
1468 =item B<$X-E<gt>shift>
1470 Removes and returns the first element of the array.
1472 =item B<$X-E<gt>unshift(list) ;>
1474 Pushes the elements of C<list> to the start of the array.
1476 =item B<$X-E<gt>length>
1478 Returns the number of elements in the array.
1480 =item B<$X-E<gt>splice(offset, length, elements);>
1482 Returns a splice of the array.
1486 =head2 Another Example
1488 Here is a more complete example that makes use of some of the methods
1489 described above. It also makes use of the API interface directly (see
1490 L<THE API INTERFACE>).
1494 my (@h, $H, $file, $i) ;
1502 $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0666, $DB_RECNO
1503 or die "Cannot open file $file: $!\n" ;
1505 # first create a text file to play with
1513 # Print the records in order.
1515 # The length method is needed here because evaluating a tied
1516 # array in a scalar context does not return the number of
1517 # elements in the array.
1519 print "\nORIGINAL\n" ;
1520 foreach $i (0 .. $H->length - 1) {
1521 print "$i: $h[$i]\n" ;
1524 # use the push & pop methods
1527 print "\nThe last record was [$a]\n" ;
1529 # and the shift & unshift methods
1531 $H->unshift("first") ;
1532 print "The first record was [$a]\n" ;
1534 # Use the API to add a new record after record 2.
1536 $H->put($i, "Newbie", R_IAFTER) ;
1538 # and a new record before record 1.
1540 $H->put($i, "New One", R_IBEFORE) ;
1545 # now print the records in reverse order
1546 print "\nREVERSE\n" ;
1547 for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
1548 { print "$i: $h[$i]\n" }
1550 # same again, but use the API functions instead
1551 print "\nREVERSE again\n" ;
1552 my ($s, $k, $v) = (0, 0, 0) ;
1553 for ($s = $H->seq($k, $v, R_LAST) ;
1555 $s = $H->seq($k, $v, R_PREV))
1556 { print "$k: $v\n" }
1561 and this is what it outputs:
1570 The last record was [four]
1571 The first record was [zero]
1595 Rather than iterating through the array, C<@h> like this:
1599 it is necessary to use either this:
1601 foreach $i (0 .. $H->length - 1)
1605 for ($a = $H->get($k, $v, R_FIRST) ;
1607 $a = $H->get($k, $v, R_NEXT) )
1611 Notice that both times the C<put> method was used the record index was
1612 specified using a variable, C<$i>, rather than the literal value
1613 itself. This is because C<put> will return the record number of the
1614 inserted line via that parameter.
1618 =head1 THE API INTERFACE
1620 As well as accessing Berkeley DB using a tied hash or array, it is also
1621 possible to make direct use of most of the API functions defined in the
1622 Berkeley DB documentation.
1624 To do this you need to store a copy of the object returned from the tie.
1626 $db = tie %hash, "DB_File", "filename" ;
1628 Once you have done that, you can access the Berkeley DB API functions
1629 as B<DB_File> methods directly like this:
1631 $db->put($key, $value, R_NOOVERWRITE) ;
1633 B<Important:> If you have saved a copy of the object returned from
1634 C<tie>, the underlying database file will I<not> be closed until both
1635 the tied variable is untied and all copies of the saved object are
1639 $db = tie %hash, "DB_File", "filename"
1640 or die "Cannot tie filename: $!" ;
1645 See L<The untie() Gotcha> for more details.
1647 All the functions defined in L<dbopen> are available except for
1648 close() and dbopen() itself. The B<DB_File> method interface to the
1649 supported functions have been implemented to mirror the way Berkeley DB
1650 works whenever possible. In particular note that:
1656 The methods return a status value. All return 0 on success.
1657 All return -1 to signify an error and set C<$!> to the exact
1658 error code. The return code 1 generally (but not always) means that the
1659 key specified did not exist in the database.
1661 Other return codes are defined. See below and in the Berkeley DB
1662 documentation for details. The Berkeley DB documentation should be used
1663 as the definitive source.
1667 Whenever a Berkeley DB function returns data via one of its parameters,
1668 the equivalent B<DB_File> method does exactly the same.
1672 If you are careful, it is possible to mix API calls with the tied
1673 hash/array interface in the same piece of code. Although only a few of
1674 the methods used to implement the tied interface currently make use of
1675 the cursor, you should always assume that the cursor has been changed
1676 any time the tied hash/array interface is used. As an example, this
1677 code will probably not do what you expect:
1679 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1680 or die "Cannot tie $filename: $!" ;
1682 # Get the first key/value pair and set the cursor
1683 $X->seq($key, $value, R_FIRST) ;
1685 # this line will modify the cursor
1686 $count = scalar keys %x ;
1688 # Get the second key/value pair.
1689 # oops, it didn't, it got the last key/value pair!
1690 $X->seq($key, $value, R_NEXT) ;
1692 The code above can be rearranged to get around the problem, like this:
1694 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1695 or die "Cannot tie $filename: $!" ;
1697 # this line will modify the cursor
1698 $count = scalar keys %x ;
1700 # Get the first key/value pair and set the cursor
1701 $X->seq($key, $value, R_FIRST) ;
1703 # Get the second key/value pair.
1705 $X->seq($key, $value, R_NEXT) ;
1709 All the constants defined in L<dbopen> for use in the flags parameters
1710 in the methods defined below are also available. Refer to the Berkeley
1711 DB documentation for the precise meaning of the flags values.
1713 Below is a list of the methods available.
1717 =item B<$status = $X-E<gt>get($key, $value [, $flags]) ;>
1719 Given a key (C<$key>) this method reads the value associated with it
1720 from the database. The value read from the database is returned in the
1721 C<$value> parameter.
1723 If the key does not exist the method returns 1.
1725 No flags are currently defined for this method.
1727 =item B<$status = $X-E<gt>put($key, $value [, $flags]) ;>
1729 Stores the key/value pair in the database.
1731 If you use either the R_IAFTER or R_IBEFORE flags, the C<$key> parameter
1732 will have the record number of the inserted key/value pair set.
1734 Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
1737 =item B<$status = $X-E<gt>del($key [, $flags]) ;>
1739 Removes all key/value pairs with key C<$key> from the database.
1741 A return code of 1 means that the requested key was not in the
1744 R_CURSOR is the only valid flag at present.
1746 =item B<$status = $X-E<gt>fd ;>
1748 Returns the file descriptor for the underlying database.
1750 See L<Locking: The Trouble with fd> for an explanation for why you should
1751 not use C<fd> to lock your database.
1753 =item B<$status = $X-E<gt>seq($key, $value, $flags) ;>
1755 This interface allows sequential retrieval from the database. See
1756 L<dbopen> for full details.
1758 Both the C<$key> and C<$value> parameters will be set to the key/value
1759 pair read from the database.
1761 The flags parameter is mandatory. The valid flag values are R_CURSOR,
1762 R_FIRST, R_LAST, R_NEXT and R_PREV.
1764 =item B<$status = $X-E<gt>sync([$flags]) ;>
1766 Flushes any cached buffers to disk.
1768 R_RECNOSYNC is the only valid flag at present.
1774 A DBM Filter is a piece of code that is be used when you I<always>
1775 want to make the same transformation to all keys and/or values in a
1778 There are four methods associated with DBM Filters. All work identically,
1779 and each is used to install (or uninstall) a single DBM Filter. Each
1780 expects a single parameter, namely a reference to a sub. The only
1781 difference between them is the place that the filter is installed.
1787 =item B<filter_store_key>
1789 If a filter has been installed with this method, it will be invoked
1790 every time you write a key to a DBM database.
1792 =item B<filter_store_value>
1794 If a filter has been installed with this method, it will be invoked
1795 every time you write a value to a DBM database.
1798 =item B<filter_fetch_key>
1800 If a filter has been installed with this method, it will be invoked
1801 every time you read a key from a DBM database.
1803 =item B<filter_fetch_value>
1805 If a filter has been installed with this method, it will be invoked
1806 every time you read a value from a DBM database.
1810 You can use any combination of the methods, from none, to all four.
1812 All filter methods return the existing filter, if present, or C<undef>
1815 To delete a filter pass C<undef> to it.
1819 When each filter is called by Perl, a local copy of C<$_> will contain
1820 the key or value to be filtered. Filtering is achieved by modifying
1821 the contents of C<$_>. The return code from the filter is ignored.
1823 =head2 An Example -- the NULL termination problem.
1825 Consider the following scenario. You have a DBM database
1826 that you need to share with a third-party C application. The C application
1827 assumes that I<all> keys and values are NULL terminated. Unfortunately
1828 when Perl writes to DBM databases it doesn't use NULL termination, so
1829 your Perl application will have to manage NULL termination itself. When
1830 you write to the database you will have to use something like this:
1832 $hash{"$key\0"} = "$value\0" ;
1834 Similarly the NULL needs to be taken into account when you are considering
1835 the length of existing keys/values.
1837 It would be much better if you could ignore the NULL terminations issue
1838 in the main application code and have a mechanism that automatically
1839 added the terminating NULL to all keys and values whenever you write to
1840 the database and have them removed when you read from the database. As I'm
1841 sure you have already guessed, this is a problem that DBM Filters can
1849 my $filename = "filt" ;
1852 my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
1853 or die "Cannot open $filename: $!\n" ;
1855 # Install DBM Filters
1856 $db->filter_fetch_key ( sub { s/\0$// } ) ;
1857 $db->filter_store_key ( sub { $_ .= "\0" } ) ;
1858 $db->filter_fetch_value( sub { s/\0$// } ) ;
1859 $db->filter_store_value( sub { $_ .= "\0" } ) ;
1861 $hash{"abc"} = "def" ;
1862 my $a = $hash{"ABC"} ;
1867 Hopefully the contents of each of the filters should be
1868 self-explanatory. Both "fetch" filters remove the terminating NULL,
1869 and both "store" filters add a terminating NULL.
1872 =head2 Another Example -- Key is a C int.
1874 Here is another real-life example. By default, whenever Perl writes to
1875 a DBM database it always writes the key and value as strings. So when
1878 $hash{12345} = "something" ;
1880 the key 12345 will get stored in the DBM database as the 5 byte string
1881 "12345". If you actually want the key to be stored in the DBM database
1882 as a C int, you will have to use C<pack> when writing, and C<unpack>
1885 Here is a DBM Filter that does it:
1891 my $filename = "filt" ;
1895 my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
1896 or die "Cannot open $filename: $!\n" ;
1898 $db->filter_fetch_key ( sub { $_ = unpack("i", $_) } ) ;
1899 $db->filter_store_key ( sub { $_ = pack ("i", $_) } ) ;
1900 $hash{123} = "def" ;
1905 This time only two filters have been used -- we only need to manipulate
1906 the contents of the key, so it wasn't necessary to install any value
1909 =head1 HINTS AND TIPS
1912 =head2 Locking: The Trouble with fd
1914 Until version 1.72 of this module, the recommended technique for locking
1915 B<DB_File> databases was to flock the filehandle returned from the "fd"
1916 function. Unfortunately this technique has been shown to be fundamentally
1917 flawed (Kudos to David Harris for tracking this down). Use it at your own
1920 The locking technique went like this.
1922 $db = tie(%db, 'DB_File', 'foo.db', O_CREAT|O_RDWR, 0644)
1923 || die "dbcreat foo.db $!";
1925 open(DB_FH, "+<&=$fd") || die "dup $!";
1926 flock (DB_FH, LOCK_EX) || die "flock: $!";
1928 $db{"Tom"} = "Jerry" ;
1930 flock(DB_FH, LOCK_UN);
1935 In simple terms, this is what happens:
1941 Use "tie" to open the database.
1945 Lock the database with fd & flock.
1949 Read & Write to the database.
1953 Unlock and close the database.
1957 Here is the crux of the problem. A side-effect of opening the B<DB_File>
1958 database in step 2 is that an initial block from the database will get
1959 read from disk and cached in memory.
1961 To see why this is a problem, consider what can happen when two processes,
1962 say "A" and "B", both want to update the same B<DB_File> database
1963 using the locking steps outlined above. Assume process "A" has already
1964 opened the database and has a write lock, but it hasn't actually updated
1965 the database yet (it has finished step 2, but not started step 3 yet). Now
1966 process "B" tries to open the same database - step 1 will succeed,
1967 but it will block on step 2 until process "A" releases the lock. The
1968 important thing to notice here is that at this point in time both
1969 processes will have cached identical initial blocks from the database.
1971 Now process "A" updates the database and happens to change some of the
1972 data held in the initial buffer. Process "A" terminates, flushing
1973 all cached data to disk and releasing the database lock. At this point
1974 the database on disk will correctly reflect the changes made by process
1977 With the lock released, process "B" can now continue. It also updates the
1978 database and unfortunately it too modifies the data that was in its
1979 initial buffer. Once that data gets flushed to disk it will overwrite
1980 some/all of the changes process "A" made to the database.
1982 The result of this scenario is at best a database that doesn't contain
1983 what you expect. At worst the database will corrupt.
1985 The above won't happen every time competing process update the same
1986 B<DB_File> database, but it does illustrate why the technique should
1989 =head2 Safe ways to lock a database
1991 Starting with version 2.x, Berkeley DB has internal support for locking.
1992 The companion module to this one, B<BerkeleyDB>, provides an interface
1993 to this locking functionality. If you are serious about locking
1994 Berkeley DB databases, I strongly recommend using B<BerkeleyDB>.
1996 If using B<BerkeleyDB> isn't an option, there are a number of modules
1997 available on CPAN that can be used to implement locking. Each one
1998 implements locking differently and has different goals in mind. It is
1999 therefore worth knowing the difference, so that you can pick the right
2000 one for your application. Here are the three locking wrappers:
2004 =item B<Tie::DB_Lock>
2006 A B<DB_File> wrapper which creates copies of the database file for
2007 read access, so that you have a kind of a multiversioning concurrent read
2008 system. However, updates are still serial. Use for databases where reads
2009 may be lengthy and consistency problems may occur.
2011 =item B<Tie::DB_LockFile>
2013 A B<DB_File> wrapper that has the ability to lock and unlock the database
2014 while it is being used. Avoids the tie-before-flock problem by simply
2015 re-tie-ing the database when you get or drop a lock. Because of the
2016 flexibility in dropping and re-acquiring the lock in the middle of a
2017 session, this can be massaged into a system that will work with long
2018 updates and/or reads if the application follows the hints in the POD
2021 =item B<DB_File::Lock>
2023 An extremely lightweight B<DB_File> wrapper that simply flocks a lockfile
2024 before tie-ing the database and drops the lock after the untie. Allows
2025 one to use the same lockfile for multiple databases to avoid deadlock
2026 problems, if desired. Use for databases where updates are reads are
2027 quick and simple flock locking semantics are enough.
2031 =head2 Sharing Databases With C Applications
2033 There is no technical reason why a Berkeley DB database cannot be
2034 shared by both a Perl and a C application.
2036 The vast majority of problems that are reported in this area boil down
2037 to the fact that C strings are NULL terminated, whilst Perl strings are
2038 not. See L<DBM FILTERS> for a generic way to work around this problem.
2040 Here is a real example. Netscape 2.0 keeps a record of the locations you
2041 visit along with the time you last visited them in a DB_HASH database.
2042 This is usually stored in the file F<~/.netscape/history.db>. The key
2043 field in the database is the location string and the value field is the
2044 time the location was last visited stored as a 4 byte binary value.
2046 If you haven't already guessed, the location string is stored with a
2047 terminating NULL. This means you need to be careful when accessing the
2050 Here is a snippet of code that is loosely based on Tom Christiansen's
2051 I<ggh> script (available from your nearest CPAN archive in
2052 F<authors/id/TOMC/scripts/nshist.gz>).
2059 my ($dotdir, $HISTORY, %hist_db, $href, $binary_time, $date) ;
2060 $dotdir = $ENV{HOME} || $ENV{LOGNAME};
2062 $HISTORY = "$dotdir/.netscape/history.db";
2064 tie %hist_db, 'DB_File', $HISTORY
2065 or die "Cannot open $HISTORY: $!\n" ;;
2067 # Dump the complete database
2068 while ( ($href, $binary_time) = each %hist_db ) {
2070 # remove the terminating NULL
2071 $href =~ s/\x00$// ;
2073 # convert the binary time into a user friendly string
2074 $date = localtime unpack("V", $binary_time);
2075 print "$date $href\n" ;
2078 # check for the existence of a specific key
2079 # remember to add the NULL
2080 if ( $binary_time = $hist_db{"http://mox.perl.com/\x00"} ) {
2081 $date = localtime unpack("V", $binary_time) ;
2082 print "Last visited mox.perl.com on $date\n" ;
2085 print "Never visited mox.perl.com\n"
2090 =head2 The untie() Gotcha
2092 If you make use of the Berkeley DB API, it is I<very> strongly
2093 recommended that you read L<perltie/The untie Gotcha>.
2095 Even if you don't currently make use of the API interface, it is still
2098 Here is an example which illustrates the problem from a B<DB_File>
2107 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
2108 or die "Cannot tie first time: $!" ;
2114 tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
2115 or die "Cannot tie second time: $!" ;
2119 When run, the script will produce this error message:
2121 Cannot tie second time: Invalid argument at bad.file line 14.
2123 Although the error message above refers to the second tie() statement
2124 in the script, the source of the problem is really with the untie()
2125 statement that precedes it.
2127 Having read L<perltie> you will probably have already guessed that the
2128 error is caused by the extra copy of the tied object stored in C<$X>.
2129 If you haven't, then the problem boils down to the fact that the
2130 B<DB_File> destructor, DESTROY, will not be called until I<all>
2131 references to the tied object are destroyed. Both the tied variable,
2132 C<%x>, and C<$X> above hold a reference to the object. The call to
2133 untie() will destroy the first, but C<$X> still holds a valid
2134 reference, so the destructor will not get called and the database file
2135 F<tst.fil> will remain open. The fact that Berkeley DB then reports the
2136 attempt to open a database that is already open via the catch-all
2137 "Invalid argument" doesn't help.
2139 If you run the script with the C<-w> flag the error message becomes:
2141 untie attempted while 1 inner references still exist at bad.file line 12.
2142 Cannot tie second time: Invalid argument at bad.file line 14.
2144 which pinpoints the real problem. Finally the script can now be
2145 modified to fix the original problem by destroying the API object
2154 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
2158 =head1 COMMON QUESTIONS
2160 =head2 Why is there Perl source in my database?
2162 If you look at the contents of a database file created by DB_File,
2163 there can sometimes be part of a Perl script included in it.
2165 This happens because Berkeley DB uses dynamic memory to allocate
2166 buffers which will subsequently be written to the database file. Being
2167 dynamic, the memory could have been used for anything before DB
2168 malloced it. As Berkeley DB doesn't clear the memory once it has been
2169 allocated, the unused portions will contain random junk. In the case
2170 where a Perl script gets written to the database, the random junk will
2171 correspond to an area of dynamic memory that happened to be used during
2172 the compilation of the script.
2174 Unless you don't like the possibility of there being part of your Perl
2175 scripts embedded in a database file, this is nothing to worry about.
2177 =head2 How do I store complex data structures with DB_File?
2179 Although B<DB_File> cannot do this directly, there is a module which
2180 can layer transparently over B<DB_File> to accomplish this feat.
2182 Check out the MLDBM module, available on CPAN in the directory
2183 F<modules/by-module/MLDBM>.
2185 =head2 What does "Invalid Argument" mean?
2187 You will get this error message when one of the parameters in the
2188 C<tie> call is wrong. Unfortunately there are quite a few parameters to
2189 get wrong, so it can be difficult to figure out which one it is.
2191 Here are a couple of possibilities:
2197 Attempting to reopen a database without closing it.
2201 Using the O_WRONLY flag.
2205 =head2 What does "Bareword 'DB_File' not allowed" mean?
2207 You will encounter this particular error message when you have the
2208 C<strict 'subs'> pragma (or the full strict pragma) in your script.
2209 Consider this script:
2215 tie %x, DB_File, "filename" ;
2217 Running it produces the error in question:
2219 Bareword "DB_File" not allowed while "strict subs" in use
2221 To get around the error, place the word C<DB_File> in either single or
2222 double quotes, like this:
2224 tie %x, "DB_File", "filename" ;
2226 Although it might seem like a real pain, it is really worth the effort
2227 of having a C<use strict> in all your scripts.
2231 Articles that are either about B<DB_File> or make use of it.
2237 I<Full-Text Searching in Perl>, Tim Kientzle (tkientzle@ddj.com),
2238 Dr. Dobb's Journal, Issue 295, January 1999, pp 34-41
2244 Moved to the Changes file.
2248 Some older versions of Berkeley DB had problems with fixed length
2249 records using the RECNO file format. This problem has been fixed since
2250 version 1.85 of Berkeley DB.
2252 I am sure there are bugs in the code. If you do find any, or can
2253 suggest any enhancements, I would welcome your comments.
2257 B<DB_File> comes with the standard Perl source distribution. Look in
2258 the directory F<ext/DB_File>. Given the amount of time between releases
2259 of Perl the version that ships with Perl is quite likely to be out of
2260 date, so the most recent version can always be found on CPAN (see
2261 L<perlmodlib/CPAN> for details), in the directory
2262 F<modules/by-module/DB_File>.
2264 This version of B<DB_File> will work with either version 1.x, 2.x or
2265 3.x of Berkeley DB, but is limited to the functionality provided by
2268 The official web site for Berkeley DB is F<http://www.oracle.com/technology/products/berkeley-db/db/index.html>.
2269 All versions of Berkeley DB are available there.
2271 Alternatively, Berkeley DB version 1 is available at your nearest CPAN
2272 archive in F<src/misc/db.1.85.tar.gz>.
2276 Copyright (c) 1995-2012 Paul Marquess. All rights reserved. This program
2277 is free software; you can redistribute it and/or modify it under the
2278 same terms as Perl itself.
2280 Although B<DB_File> is covered by the Perl license, the library it
2281 makes use of, namely Berkeley DB, is not. Berkeley DB has its own
2282 copyright and its own license. Please take the time to read it.
2284 Here are a few words taken from the Berkeley DB FAQ (at
2285 F<http://www.oracle.com/technology/products/berkeley-db/db/index.html>) regarding the license:
2287 Do I have to license DB to use it in Perl scripts?
2289 No. The Berkeley DB license requires that software that uses
2290 Berkeley DB be freely redistributable. In the case of Perl, that
2291 software is Perl, and not your scripts. Any Perl scripts that you
2292 write are your property, including scripts that make use of
2293 Berkeley DB. Neither the Perl license nor the Berkeley DB license
2294 place any restriction on what you may do with them.
2296 If you are in any doubt about the license situation, contact either the
2297 Berkeley DB authors or the author of DB_File. See L<"AUTHOR"> for details.
2302 L<perl>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>,
2307 The DB_File interface was written by Paul Marquess
2308 E<lt>pmqs@cpan.orgE<gt>.