tie array changes to core and tests
[p5sagit/p5-mst-13.2.git] / ext / DB_File / DB_File.pm
1 # DB_File.pm -- Perl 5 interface to Berkeley DB 
2 #
3 # written by Paul Marquess (pmarquess@bfsec.bt.co.uk)
4 # last modified 20th Nov 1997
5 # version 1.56
6 #
7 #     Copyright (c) 1995, 1996, 1997 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.
10
11
12 package DB_File::HASHINFO ;
13
14 require 5.003 ;
15
16 use strict;
17 use Carp;
18 require Tie::Hash;
19 @DB_File::HASHINFO::ISA = qw(Tie::Hash);
20
21 sub new
22 {
23     my $pkg = shift ;
24     my %x ;
25     tie %x, $pkg ;
26     bless \%x, $pkg ;
27 }
28
29
30 sub TIEHASH
31 {
32     my $pkg = shift ;
33
34     bless { VALID => { map {$_, 1} 
35                        qw( bsize ffactor nelem cachesize hash lorder)
36                      }, 
37             GOT   => {}
38           }, $pkg ;
39 }
40
41
42 sub FETCH 
43 {  
44     my $self  = shift ;
45     my $key   = shift ;
46
47     return $self->{GOT}{$key} if exists $self->{VALID}{$key}  ;
48
49     my $pkg = ref $self ;
50     croak "${pkg}::FETCH - Unknown element '$key'" ;
51 }
52
53
54 sub STORE 
55 {
56     my $self  = shift ;
57     my $key   = shift ;
58     my $value = shift ;
59
60     if ( exists $self->{VALID}{$key} )
61     {
62         $self->{GOT}{$key} = $value ;
63         return ;
64     }
65     
66     my $pkg = ref $self ;
67     croak "${pkg}::STORE - Unknown element '$key'" ;
68 }
69
70 sub DELETE 
71 {
72     my $self = shift ;
73     my $key  = shift ;
74
75     if ( exists $self->{VALID}{$key} )
76     {
77         delete $self->{GOT}{$key} ;
78         return ;
79     }
80     
81     my $pkg = ref $self ;
82     croak "DB_File::HASHINFO::DELETE - Unknown element '$key'" ;
83 }
84
85 sub EXISTS
86 {
87     my $self = shift ;
88     my $key  = shift ;
89
90     exists $self->{VALID}{$key} ;
91 }
92
93 sub NotHere
94 {
95     my $self = shift ;
96     my $method = shift ;
97
98     croak ref($self) . " does not define the method ${method}" ;
99 }
100
101 sub FIRSTKEY { my $self = shift ; $self->NotHere("FIRSTKEY") }
102 sub NEXTKEY  { my $self = shift ; $self->NotHere("NEXTKEY") }
103 sub CLEAR    { my $self = shift ; $self->NotHere("CLEAR") }
104
105 package DB_File::RECNOINFO ;
106
107 use strict ;
108
109 @DB_File::RECNOINFO::ISA = qw(DB_File::HASHINFO) ;  
110
111 sub TIEHASH
112 {
113     my $pkg = shift ;
114
115     bless { VALID => { map {$_, 1} 
116                        qw( bval cachesize psize flags lorder reclen bfname )
117                      },
118             GOT   => {},
119           }, $pkg ;
120 }
121
122 package DB_File::BTREEINFO ;
123
124 use strict ;
125
126 @DB_File::BTREEINFO::ISA = qw(DB_File::HASHINFO) ;
127
128 sub TIEHASH
129 {
130     my $pkg = shift ;
131
132     bless { VALID => { map {$_, 1} 
133                        qw( flags cachesize maxkeypage minkeypage psize 
134                            compare prefix lorder )
135                      },
136             GOT   => {},
137           }, $pkg ;
138 }
139
140
141 package DB_File ;
142
143 use strict;
144 use vars qw($VERSION @ISA @EXPORT $AUTOLOAD $DB_BTREE $DB_HASH $DB_RECNO $db_version) ;
145 use Carp;
146
147
148 $VERSION = "1.56" ;
149
150 #typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
151 $DB_BTREE = new DB_File::BTREEINFO ;
152 $DB_HASH  = new DB_File::HASHINFO ;
153 $DB_RECNO = new DB_File::RECNOINFO ;
154
155 require Tie::Hash;
156 require Exporter;
157 use AutoLoader;
158 require DynaLoader;
159 @ISA = qw(Tie::Hash Exporter DynaLoader);
160 @EXPORT = qw(
161         $DB_BTREE $DB_HASH $DB_RECNO 
162
163         BTREEMAGIC
164         BTREEVERSION
165         DB_LOCK
166         DB_SHMEM
167         DB_TXN
168         HASHMAGIC
169         HASHVERSION
170         MAX_PAGE_NUMBER
171         MAX_PAGE_OFFSET
172         MAX_REC_NUMBER
173         RET_ERROR
174         RET_SPECIAL
175         RET_SUCCESS
176         R_CURSOR
177         R_DUP
178         R_FIRST
179         R_FIXEDLEN
180         R_IAFTER
181         R_IBEFORE
182         R_LAST
183         R_NEXT
184         R_NOKEY
185         R_NOOVERWRITE
186         R_PREV
187         R_RECNOSYNC
188         R_SETCURSOR
189         R_SNAPSHOT
190         __R_UNUSED
191
192 );  
193
194 sub FETCHSIZE
195
196     my $self = shift ;
197     return $self->length - 1;
198 }
199
200 sub AUTOLOAD {
201     my($constname);
202     ($constname = $AUTOLOAD) =~ s/.*:://;
203     my $val = constant($constname, @_ ? $_[0] : 0);
204     if ($! != 0) {
205         if ($! =~ /Invalid/) {
206             $AutoLoader::AUTOLOAD = $AUTOLOAD;
207             goto &AutoLoader::AUTOLOAD;
208         }
209         else {
210             my($pack,$file,$line) = caller;
211             croak "Your vendor has not defined DB macro $constname, used at $file line $line.
212 ";
213         }
214     }
215     eval "sub $AUTOLOAD { $val }";
216     goto &$AUTOLOAD;
217 }
218
219
220 eval {
221     # Make all Fcntl O_XXX constants available for importing
222     require Fcntl;
223     my @O = grep /^O_/, @Fcntl::EXPORT;
224     Fcntl->import(@O);  # first we import what we want to export
225     push(@EXPORT, @O);
226 };
227
228 ## import borrowed from IO::File
229 ##   exports Fcntl constants if available.
230 #sub import {
231 #    my $pkg = shift;
232 #    my $callpkg = caller;
233 #    Exporter::export $pkg, $callpkg, @_;
234 #    eval {
235 #        require Fcntl;
236 #        Exporter::export 'Fcntl', $callpkg, '/^O_/';
237 #    };
238 #}
239
240 bootstrap DB_File $VERSION;
241
242 # Preloaded methods go here.  Autoload methods go after __END__, and are
243 # processed by the autosplit program.
244
245 sub tie_hash_or_array
246 {
247     my (@arg) = @_ ;
248     my $tieHASH = ( (caller(1))[3] =~ /TIEHASH/ ) ;
249
250     $arg[4] = tied %{ $arg[4] } 
251         if @arg >= 5 && ref $arg[4] && $arg[4] =~ /=HASH/ && tied %{ $arg[4] } ;
252
253     # make recno in Berkeley DB version 2 work like recno in version 1.
254     if ($db_version > 1 and defined $arg[4] and $arg[4] =~ /RECNO/ and 
255         $arg[1] and ! -e $arg[1]) {
256         open(FH, ">$arg[1]") or return undef ;
257         close FH ;
258         chmod $arg[3] ? $arg[3] : 0666 , $arg[1] ;
259     }
260
261     DoTie_($tieHASH, @arg) ;
262 }
263
264 sub TIEHASH
265 {
266     tie_hash_or_array(@_) ;
267 }
268
269 sub TIEARRAY
270 {
271     tie_hash_or_array(@_) ;
272 }
273
274 sub CLEAR {
275     my $self = shift;
276     my $key = "" ;
277     my $value = "" ;
278     my $status = $self->seq($key, $value, R_FIRST());
279     my @keys;
280  
281     while ($status == 0) {
282         push @keys, $key;
283         $status = $self->seq($key, $value, R_NEXT());
284     }
285     foreach $key (reverse @keys) {
286         my $s = $self->del($key); 
287     }
288 }
289
290 sub get_dup
291 {
292     croak "Usage: \$db->get_dup(key [,flag])\n"
293         unless @_ == 2 or @_ == 3 ;
294  
295     my $db        = shift ;
296     my $key       = shift ;
297     my $flag      = shift ;
298     my $value     = 0 ;
299     my $origkey   = $key ;
300     my $wantarray = wantarray ;
301     my %values    = () ;
302     my @values    = () ;
303     my $counter   = 0 ;
304     my $status    = 0 ;
305  
306     # iterate through the database until either EOF ($status == 0)
307     # or a different key is encountered ($key ne $origkey).
308     for ($status = $db->seq($key, $value, R_CURSOR()) ;
309          $status == 0 and $key eq $origkey ;
310          $status = $db->seq($key, $value, R_NEXT()) ) {
311  
312         # save the value or count number of matches
313         if ($wantarray) {
314             if ($flag)
315                 { ++ $values{$value} }
316             else
317                 { push (@values, $value) }
318         }
319         else
320             { ++ $counter }
321      
322     }
323  
324     return ($wantarray ? ($flag ? %values : @values) : $counter) ;
325 }
326
327
328 1;
329 __END__
330
331 =head1 NAME
332
333 DB_File - Perl5 access to Berkeley DB version 1.x
334
335 =head1 SYNOPSIS
336
337  use DB_File ;
338  
339  [$X =] tie %hash,  'DB_File', [$filename, $flags, $mode, $DB_HASH] ;
340  [$X =] tie %hash,  'DB_File', $filename, $flags, $mode, $DB_BTREE ;
341  [$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ;
342
343  $status = $X->del($key [, $flags]) ;
344  $status = $X->put($key, $value [, $flags]) ;
345  $status = $X->get($key, $value [, $flags]) ;
346  $status = $X->seq($key, $value, $flags) ;
347  $status = $X->sync([$flags]) ;
348  $status = $X->fd ;
349
350  # BTREE only
351  $count = $X->get_dup($key) ;
352  @list  = $X->get_dup($key) ;
353  %list  = $X->get_dup($key, 1) ;
354
355  # RECNO only
356  $a = $X->length;
357  $a = $X->pop ;
358  $X->push(list);
359  $a = $X->shift;
360  $X->unshift(list);
361
362  untie %hash ;
363  untie @array ;
364
365 =head1 DESCRIPTION
366
367 B<DB_File> is a module which allows Perl programs to make use of the
368 facilities provided by Berkeley DB version 1.x (if you have a newer
369 version of DB, see L<Using DB_File with Berkeley DB version 2>). It is
370 assumed that you have a copy of the Berkeley DB manual pages at hand
371 when reading this documentation. The interface defined here mirrors the
372 Berkeley DB interface closely.
373
374 Berkeley DB is a C library which provides a consistent interface to a
375 number of database formats.  B<DB_File> provides an interface to all
376 three of the database types currently supported by Berkeley DB.
377
378 The file types are:
379
380 =over 5
381
382 =item B<DB_HASH>
383
384 This database type allows arbitrary key/value pairs to be stored in data
385 files. This is equivalent to the functionality provided by other
386 hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
387 the files created using DB_HASH are not compatible with any of the
388 other packages mentioned.
389
390 A default hashing algorithm, which will be adequate for most
391 applications, is built into Berkeley DB. If you do need to use your own
392 hashing algorithm it is possible to write your own in Perl and have
393 B<DB_File> use it instead.
394
395 =item B<DB_BTREE>
396
397 The btree format allows arbitrary key/value pairs to be stored in a
398 sorted, balanced binary tree.
399
400 As with the DB_HASH format, it is possible to provide a user defined
401 Perl routine to perform the comparison of keys. By default, though, the
402 keys are stored in lexical order.
403
404 =item B<DB_RECNO>
405
406 DB_RECNO allows both fixed-length and variable-length flat text files
407 to be manipulated using the same key/value pair interface as in DB_HASH
408 and DB_BTREE.  In this case the key will consist of a record (line)
409 number.
410
411 =back
412
413 =head2 Using DB_File with Berkeley DB version 2
414
415 Although B<DB_File> is intended to be used with Berkeley DB version 1,
416 it can also be used with version 2. In this case the interface is
417 limited to the functionality provided by Berkeley DB 1.x. Anywhere the
418 version 2 interface differs, B<DB_File> arranges for it to work like
419 version 1. This feature allows B<DB_File> scripts that were built with
420 version 1 to be migrated to version 2 without any changes.
421
422 If you want to make use of the new features available in Berkeley DB
423 2.x, use the Perl module B<BerkeleyDB> instead.
424
425 At the time of writing this document the B<BerkeleyDB> module is still
426 alpha quality (the version number is < 1.0), and so unsuitable for use
427 in any serious development work. Once its version number is >= 1.0, it
428 is considered stable enough for real work.
429
430 B<Note:> The database file format has changed in Berkeley DB version 2.
431 If you cannot recreate your databases, you must dump any existing
432 databases with the C<db_dump185> utility that comes with Berkeley DB.
433 Once you have upgraded DB_File to use Berkeley DB version 2, your
434 databases can be recreated using C<db_load>. Refer to the Berkeley DB
435 documentation for further details.
436
437 Please read L<COPYRIGHT> before using version 2.x of Berkeley DB with
438 DB_File.
439
440 =head2 Interface to Berkeley DB
441
442 B<DB_File> allows access to Berkeley DB files using the tie() mechanism
443 in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
444 allows B<DB_File> to access Berkeley DB files using either an
445 associative array (for DB_HASH & DB_BTREE file types) or an ordinary
446 array (for the DB_RECNO file type).
447
448 In addition to the tie() interface, it is also possible to access most
449 of the functions provided in the Berkeley DB API directly.
450 See L<THE API INTERFACE>.
451
452 =head2 Opening a Berkeley DB Database File
453
454 Berkeley DB uses the function dbopen() to open or create a database.
455 Here is the C prototype for dbopen():
456
457       DB*
458       dbopen (const char * file, int flags, int mode, 
459               DBTYPE type, const void * openinfo)
460
461 The parameter C<type> is an enumeration which specifies which of the 3
462 interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
463 Depending on which of these is actually chosen, the final parameter,
464 I<openinfo> points to a data structure which allows tailoring of the
465 specific interface method.
466
467 This interface is handled slightly differently in B<DB_File>. Here is
468 an equivalent call using B<DB_File>:
469
470         tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
471
472 The C<filename>, C<flags> and C<mode> parameters are the direct
473 equivalent of their dbopen() counterparts. The final parameter $DB_HASH
474 performs the function of both the C<type> and C<openinfo> parameters in
475 dbopen().
476
477 In the example above $DB_HASH is actually a pre-defined reference to a
478 hash object. B<DB_File> has three of these pre-defined references.
479 Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
480
481 The keys allowed in each of these pre-defined references is limited to
482 the names used in the equivalent C structure. So, for example, the
483 $DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
484 C<ffactor>, C<hash>, C<lorder> and C<nelem>. 
485
486 To change one of these elements, just assign to it like this:
487
488         $DB_HASH->{'cachesize'} = 10000 ;
489
490 The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
491 usually adequate for most applications.  If you do need to create extra
492 instances of these objects, constructors are available for each file
493 type.
494
495 Here are examples of the constructors and the valid options available
496 for DB_HASH, DB_BTREE and DB_RECNO respectively.
497
498      $a = new DB_File::HASHINFO ;
499      $a->{'bsize'} ;
500      $a->{'cachesize'} ;
501      $a->{'ffactor'};
502      $a->{'hash'} ;
503      $a->{'lorder'} ;
504      $a->{'nelem'} ;
505
506      $b = new DB_File::BTREEINFO ;
507      $b->{'flags'} ;
508      $b->{'cachesize'} ;
509      $b->{'maxkeypage'} ;
510      $b->{'minkeypage'} ;
511      $b->{'psize'} ;
512      $b->{'compare'} ;
513      $b->{'prefix'} ;
514      $b->{'lorder'} ;
515
516      $c = new DB_File::RECNOINFO ;
517      $c->{'bval'} ;
518      $c->{'cachesize'} ;
519      $c->{'psize'} ;
520      $c->{'flags'} ;
521      $c->{'lorder'} ;
522      $c->{'reclen'} ;
523      $c->{'bfname'} ;
524
525 The values stored in the hashes above are mostly the direct equivalent
526 of their C counterpart. Like their C counterparts, all are set to a
527 default values - that means you don't have to set I<all> of the
528 values when you only want to change one. Here is an example:
529
530      $a = new DB_File::HASHINFO ;
531      $a->{'cachesize'} =  12345 ;
532      tie %y, 'DB_File', "filename", $flags, 0777, $a ;
533
534 A few of the options need extra discussion here. When used, the C
535 equivalent of the keys C<hash>, C<compare> and C<prefix> store pointers
536 to C functions. In B<DB_File> these keys are used to store references
537 to Perl subs. Below are templates for each of the subs:
538
539     sub hash
540     {
541         my ($data) = @_ ;
542         ...
543         # return the hash value for $data
544         return $hash ;
545     }
546
547     sub compare
548     {
549         my ($key, $key2) = @_ ;
550         ...
551         # return  0 if $key1 eq $key2
552         #        -1 if $key1 lt $key2
553         #         1 if $key1 gt $key2
554         return (-1 , 0 or 1) ;
555     }
556
557     sub prefix
558     {
559         my ($key, $key2) = @_ ;
560         ...
561         # return number of bytes of $key2 which are 
562         # necessary to determine that it is greater than $key1
563         return $bytes ;
564     }
565
566 See L<Changing the BTREE sort order> for an example of using the
567 C<compare> template.
568
569 If you are using the DB_RECNO interface and you intend making use of
570 C<bval>, you should check out L<The 'bval' Option>.
571
572 =head2 Default Parameters
573
574 It is possible to omit some or all of the final 4 parameters in the
575 call to C<tie> and let them take default values. As DB_HASH is the most
576 common file format used, the call:
577
578     tie %A, "DB_File", "filename" ;
579
580 is equivalent to:
581
582     tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
583
584 It is also possible to omit the filename parameter as well, so the
585 call:
586
587     tie %A, "DB_File" ;
588
589 is equivalent to:
590
591     tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
592
593 See L<In Memory Databases> for a discussion on the use of C<undef>
594 in place of a filename.
595
596 =head2 In Memory Databases
597
598 Berkeley DB allows the creation of in-memory databases by using NULL
599 (that is, a C<(char *)0> in C) in place of the filename.  B<DB_File>
600 uses C<undef> instead of NULL to provide this functionality.
601
602 =head1 DB_HASH
603
604 The DB_HASH file format is probably the most commonly used of the three
605 file formats that B<DB_File> supports. It is also very straightforward
606 to use.
607
608 =head2 A Simple Example
609
610 This example shows how to create a database, add key/value pairs to the
611 database, delete keys/value pairs and finally how to enumerate the
612 contents of the database.
613
614     use strict ;
615     use DB_File ;
616     use vars qw( %h $k $v ) ;
617
618     tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0640, $DB_HASH 
619         or die "Cannot open file 'fruit': $!\n";
620
621     # Add a few key/value pairs to the file
622     $h{"apple"} = "red" ;
623     $h{"orange"} = "orange" ;
624     $h{"banana"} = "yellow" ;
625     $h{"tomato"} = "red" ;
626
627     # Check for existence of a key
628     print "Banana Exists\n\n" if $h{"banana"} ;
629
630     # Delete a key/value pair.
631     delete $h{"apple"} ;
632
633     # print the contents of the file
634     while (($k, $v) = each %h)
635       { print "$k -> $v\n" }
636
637     untie %h ;
638
639 here is the output:
640
641     Banana Exists
642  
643     orange -> orange
644     tomato -> red
645     banana -> yellow
646
647 Note that the like ordinary associative arrays, the order of the keys
648 retrieved is in an apparently random order.
649
650 =head1 DB_BTREE
651
652 The DB_BTREE format is useful when you want to store data in a given
653 order. By default the keys will be stored in lexical order, but as you
654 will see from the example shown in the next section, it is very easy to
655 define your own sorting function.
656
657 =head2 Changing the BTREE sort order
658
659 This script shows how to override the default sorting algorithm that
660 BTREE uses. Instead of using the normal lexical ordering, a case
661 insensitive compare function will be used.
662
663     use strict ;
664     use DB_File ;
665
666     my %h ;
667
668     sub Compare
669     {
670         my ($key1, $key2) = @_ ;
671         "\L$key1" cmp "\L$key2" ;
672     }
673
674     # specify the Perl sub that will do the comparison
675     $DB_BTREE->{'compare'} = \&Compare ;
676
677     tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0640, $DB_BTREE 
678         or die "Cannot open file 'tree': $!\n" ;
679
680     # Add a key/value pair to the file
681     $h{'Wall'} = 'Larry' ;
682     $h{'Smith'} = 'John' ;
683     $h{'mouse'} = 'mickey' ;
684     $h{'duck'}  = 'donald' ;
685
686     # Delete
687     delete $h{"duck"} ;
688
689     # Cycle through the keys printing them in order.
690     # Note it is not necessary to sort the keys as
691     # the btree will have kept them in order automatically.
692     foreach (keys %h)
693       { print "$_\n" }
694
695     untie %h ;
696
697 Here is the output from the code above.
698
699     mouse
700     Smith
701     Wall
702
703 There are a few point to bear in mind if you want to change the
704 ordering in a BTREE database:
705
706 =over 5
707
708 =item 1.
709
710 The new compare function must be specified when you create the database.
711
712 =item 2.
713
714 You cannot change the ordering once the database has been created. Thus
715 you must use the same compare function every time you access the
716 database.
717
718 =back 
719
720 =head2 Handling Duplicate Keys 
721
722 The BTREE file type optionally allows a single key to be associated
723 with an arbitrary number of values. This option is enabled by setting
724 the flags element of C<$DB_BTREE> to R_DUP when creating the database.
725
726 There are some difficulties in using the tied hash interface if you
727 want to manipulate a BTREE database with duplicate keys. Consider this
728 code:
729
730     use strict ;
731     use DB_File ;
732
733     use vars qw($filename %h ) ;
734
735     $filename = "tree" ;
736     unlink $filename ;
737  
738     # Enable duplicate records
739     $DB_BTREE->{'flags'} = R_DUP ;
740  
741     tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE 
742         or die "Cannot open $filename: $!\n";
743  
744     # Add some key/value pairs to the file
745     $h{'Wall'} = 'Larry' ;
746     $h{'Wall'} = 'Brick' ; # Note the duplicate key
747     $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
748     $h{'Smith'} = 'John' ;
749     $h{'mouse'} = 'mickey' ;
750
751     # iterate through the associative array
752     # and print each key/value pair.
753     foreach (keys %h)
754       { print "$_  -> $h{$_}\n" }
755
756     untie %h ;
757
758 Here is the output:
759
760     Smith   -> John
761     Wall    -> Larry
762     Wall    -> Larry
763     Wall    -> Larry
764     mouse   -> mickey
765
766 As you can see 3 records have been successfully created with key C<Wall>
767 - the only thing is, when they are retrieved from the database they
768 I<seem> to have the same value, namely C<Larry>. The problem is caused
769 by the way that the associative array interface works. Basically, when
770 the associative array interface is used to fetch the value associated
771 with a given key, it will only ever retrieve the first value.
772
773 Although it may not be immediately obvious from the code above, the
774 associative array interface can be used to write values with duplicate
775 keys, but it cannot be used to read them back from the database.
776
777 The way to get around this problem is to use the Berkeley DB API method
778 called C<seq>.  This method allows sequential access to key/value
779 pairs. See L<THE API INTERFACE> for details of both the C<seq> method
780 and the API in general.
781
782 Here is the script above rewritten using the C<seq> API method.
783
784     use strict ;
785     use DB_File ;
786  
787     use vars qw($filename $x %h $status $key $value) ;
788
789     $filename = "tree" ;
790     unlink $filename ;
791  
792     # Enable duplicate records
793     $DB_BTREE->{'flags'} = R_DUP ;
794  
795     $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE 
796         or die "Cannot open $filename: $!\n";
797  
798     # Add some key/value pairs to the file
799     $h{'Wall'} = 'Larry' ;
800     $h{'Wall'} = 'Brick' ; # Note the duplicate key
801     $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
802     $h{'Smith'} = 'John' ;
803     $h{'mouse'} = 'mickey' ;
804  
805     # iterate through the btree using seq
806     # and print each key/value pair.
807     $key = $value = 0 ;
808     for ($status = $x->seq($key, $value, R_FIRST) ;
809          $status == 0 ;
810          $status = $x->seq($key, $value, R_NEXT) )
811       {  print "$key -> $value\n" }
812  
813     undef $x ;
814     untie %h ;
815
816 that prints:
817
818     Smith   -> John
819     Wall    -> Brick
820     Wall    -> Brick
821     Wall    -> Larry
822     mouse   -> mickey
823
824 This time we have got all the key/value pairs, including the multiple
825 values associated with the key C<Wall>.
826
827 =head2 The get_dup() Method
828
829 B<DB_File> comes with a utility method, called C<get_dup>, to assist in
830 reading duplicate values from BTREE databases. The method can take the
831 following forms:
832
833     $count = $x->get_dup($key) ;
834     @list  = $x->get_dup($key) ;
835     %list  = $x->get_dup($key, 1) ;
836
837 In a scalar context the method returns the number of values associated
838 with the key, C<$key>.
839
840 In list context, it returns all the values which match C<$key>. Note
841 that the values will be returned in an apparently random order.
842
843 In list context, if the second parameter is present and evaluates
844 TRUE, the method returns an associative array. The keys of the
845 associative array correspond to the values that matched in the BTREE
846 and the values of the array are a count of the number of times that
847 particular value occurred in the BTREE.
848
849 So assuming the database created above, we can use C<get_dup> like
850 this:
851
852     my $cnt  = $x->get_dup("Wall") ;
853     print "Wall occurred $cnt times\n" ;
854
855     my %hash = $x->get_dup("Wall", 1) ;
856     print "Larry is there\n" if $hash{'Larry'} ;
857     print "There are $hash{'Brick'} Brick Walls\n" ;
858
859     my @list = $x->get_dup("Wall") ;
860     print "Wall =>      [@list]\n" ;
861
862     @list = $x->get_dup("Smith") ;
863     print "Smith =>     [@list]\n" ;
864  
865     @list = $x->get_dup("Dog") ;
866     print "Dog =>       [@list]\n" ;
867
868
869 and it will print:
870
871     Wall occurred 3 times
872     Larry is there
873     There are 2 Brick Walls
874     Wall =>     [Brick Brick Larry]
875     Smith =>    [John]
876     Dog =>      []
877
878 =head2 Matching Partial Keys 
879
880 The BTREE interface has a feature which allows partial keys to be
881 matched. This functionality is I<only> available when the C<seq> method
882 is used along with the R_CURSOR flag.
883
884     $x->seq($key, $value, R_CURSOR) ;
885
886 Here is the relevant quote from the dbopen man page where it defines
887 the use of the R_CURSOR flag with seq:
888
889     Note, for the DB_BTREE access method, the returned key is not
890     necessarily an exact match for the specified key. The returned key
891     is the smallest key greater than or equal to the specified key,
892     permitting partial key matches and range searches.
893
894 In the example script below, the C<match> sub uses this feature to find
895 and print the first matching key/value pair given a partial key.
896
897     use strict ;
898     use DB_File ;
899     use Fcntl ;
900
901     use vars qw($filename $x %h $st $key $value) ;
902
903     sub match
904     {
905         my $key = shift ;
906         my $value = 0;
907         my $orig_key = $key ;
908         $x->seq($key, $value, R_CURSOR) ;
909         print "$orig_key\t-> $key\t-> $value\n" ;
910     }
911
912     $filename = "tree" ;
913     unlink $filename ;
914
915     $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
916         or die "Cannot open $filename: $!\n";
917  
918     # Add some key/value pairs to the file
919     $h{'mouse'} = 'mickey' ;
920     $h{'Wall'} = 'Larry' ;
921     $h{'Walls'} = 'Brick' ; 
922     $h{'Smith'} = 'John' ;
923  
924
925     $key = $value = 0 ;
926     print "IN ORDER\n" ;
927     for ($st = $x->seq($key, $value, R_FIRST) ;
928          $st == 0 ;
929          $st = $x->seq($key, $value, R_NEXT) )
930         
931       {  print "$key -> $value\n" }
932  
933     print "\nPARTIAL MATCH\n" ;
934
935     match "Wa" ;
936     match "A" ;
937     match "a" ;
938
939     undef $x ;
940     untie %h ;
941
942 Here is the output:
943
944     IN ORDER
945     Smith -> John
946     Wall  -> Larry
947     Walls -> Brick
948     mouse -> mickey
949
950     PARTIAL MATCH
951     Wa -> Wall  -> Larry
952     A  -> Smith -> John
953     a  -> mouse -> mickey
954
955 =head1 DB_RECNO
956
957 DB_RECNO provides an interface to flat text files. Both variable and
958 fixed length records are supported.
959
960 In order to make RECNO more compatible with Perl the array offset for
961 all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
962
963 As with normal Perl arrays, a RECNO array can be accessed using
964 negative indexes. The index -1 refers to the last element of the array,
965 -2 the second last, and so on. Attempting to access an element before
966 the start of the array will raise a fatal run-time error.
967
968 =head2 The 'bval' Option
969
970 The operation of the bval option warrants some discussion. Here is the
971 definition of bval from the Berkeley DB 1.85 recno manual page:
972
973     The delimiting byte to be used to mark  the  end  of  a
974     record for variable-length records, and the pad charac-
975     ter for fixed-length records.  If no  value  is  speci-
976     fied,  newlines  (``\n'')  are  used to mark the end of
977     variable-length records and  fixed-length  records  are
978     padded with spaces.
979
980 The second sentence is wrong. In actual fact bval will only default to
981 C<"\n"> when the openinfo parameter in dbopen is NULL. If a non-NULL
982 openinfo parameter is used at all, the value that happens to be in bval
983 will be used. That means you always have to specify bval when making
984 use of any of the options in the openinfo parameter. This documentation
985 error will be fixed in the next release of Berkeley DB.
986
987 That clarifies the situation with regards Berkeley DB itself. What
988 about B<DB_File>? Well, the behavior defined in the quote above is
989 quite useful, so B<DB_File> conforms it.
990
991 That means that you can specify other options (e.g. cachesize) and
992 still have bval default to C<"\n"> for variable length records, and
993 space for fixed length records.
994
995 =head2 A Simple Example
996
997 Here is a simple example that uses RECNO.
998
999     use strict ;
1000     use DB_File ;
1001
1002     my @h ;
1003     tie @h, "DB_File", "text", O_RDWR|O_CREAT, 0640, $DB_RECNO 
1004         or die "Cannot open file 'text': $!\n" ;
1005
1006     # Add a few key/value pairs to the file
1007     $h[0] = "orange" ;
1008     $h[1] = "blue" ;
1009     $h[2] = "yellow" ;
1010
1011     # Check for existence of a key
1012     print "Element 1 Exists with value $h[1]\n" if $h[1] ;
1013
1014     # use a negative index
1015     print "The last element is $h[-1]\n" ;
1016     print "The 2nd last element is $h[-2]\n" ;
1017
1018     untie @h ;
1019
1020 Here is the output from the script:
1021
1022
1023     Element 1 Exists with value blue
1024     The last element is yellow
1025     The 2nd last element is blue
1026
1027 =head2 Extra Methods
1028
1029 As you can see from the example above, the tied array interface is
1030 quite limited. To make the interface more useful, a number of methods
1031 are supplied with B<DB_File> to simulate the standard array operations
1032 that are not currently implemented in Perl's tied array interface. All
1033 these methods are accessed via the object returned from the tie call.
1034
1035 Here are the methods:
1036
1037 =over 5
1038
1039 =item B<$X-E<gt>push(list) ;>
1040
1041 Pushes the elements of C<list> to the end of the array.
1042
1043 =item B<$value = $X-E<gt>pop ;>
1044
1045 Removes and returns the last element of the array.
1046
1047 =item B<$X-E<gt>shift>
1048
1049 Removes and returns the first element of the array.
1050
1051 =item B<$X-E<gt>unshift(list) ;>
1052
1053 Pushes the elements of C<list> to the start of the array.
1054
1055 =item B<$X-E<gt>length>
1056
1057 Returns the number of elements in the array.
1058
1059 =back
1060
1061 =head2 Another Example
1062
1063 Here is a more complete example that makes use of some of the methods
1064 described above. It also makes use of the API interface directly (see 
1065 L<THE API INTERFACE>).
1066
1067     use strict ;
1068     use vars qw(@h $H $file $i) ;
1069     use DB_File ;
1070     use Fcntl ;
1071     
1072     $file = "text" ;
1073
1074     unlink $file ;
1075
1076     $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0640, $DB_RECNO 
1077         or die "Cannot open file $file: $!\n" ;
1078     
1079     # first create a text file to play with
1080     $h[0] = "zero" ;
1081     $h[1] = "one" ;
1082     $h[2] = "two" ;
1083     $h[3] = "three" ;
1084     $h[4] = "four" ;
1085
1086     
1087     # Print the records in order.
1088     #
1089     # The length method is needed here because evaluating a tied
1090     # array in a scalar context does not return the number of
1091     # elements in the array.  
1092
1093     print "\nORIGINAL\n" ;
1094     foreach $i (0 .. $H->length - 1) {
1095         print "$i: $h[$i]\n" ;
1096     }
1097
1098     # use the push & pop methods
1099     $a = $H->pop ;
1100     $H->push("last") ;
1101     print "\nThe last record was [$a]\n" ;
1102
1103     # and the shift & unshift methods
1104     $a = $H->shift ;
1105     $H->unshift("first") ;
1106     print "The first record was [$a]\n" ;
1107
1108     # Use the API to add a new record after record 2.
1109     $i = 2 ;
1110     $H->put($i, "Newbie", R_IAFTER) ;
1111
1112     # and a new record before record 1.
1113     $i = 1 ;
1114     $H->put($i, "New One", R_IBEFORE) ;
1115
1116     # delete record 3
1117     $H->del(3) ;
1118
1119     # now print the records in reverse order
1120     print "\nREVERSE\n" ;
1121     for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
1122       { print "$i: $h[$i]\n" }
1123
1124     # same again, but use the API functions instead
1125     print "\nREVERSE again\n" ;
1126     my ($s, $k, $v)  = (0, 0, 0) ;
1127     for ($s = $H->seq($k, $v, R_LAST) ; 
1128              $s == 0 ; 
1129              $s = $H->seq($k, $v, R_PREV))
1130       { print "$k: $v\n" }
1131
1132     undef $H ;
1133     untie @h ;
1134
1135 and this is what it outputs:
1136
1137     ORIGINAL
1138     0: zero
1139     1: one
1140     2: two
1141     3: three
1142     4: four
1143
1144     The last record was [four]
1145     The first record was [zero]
1146
1147     REVERSE
1148     5: last
1149     4: three
1150     3: Newbie
1151     2: one
1152     1: New One
1153     0: first
1154
1155     REVERSE again
1156     5: last
1157     4: three
1158     3: Newbie
1159     2: one
1160     1: New One
1161     0: first
1162
1163 Notes:
1164
1165 =over 5
1166
1167 =item 1.
1168
1169 Rather than iterating through the array, C<@h> like this:
1170
1171     foreach $i (@h)
1172
1173 it is necessary to use either this:
1174
1175     foreach $i (0 .. $H->length - 1) 
1176
1177 or this:
1178
1179     for ($a = $H->get($k, $v, R_FIRST) ;
1180          $a == 0 ;
1181          $a = $H->get($k, $v, R_NEXT) )
1182
1183 =item 2.
1184
1185 Notice that both times the C<put> method was used the record index was
1186 specified using a variable, C<$i>, rather than the literal value
1187 itself. This is because C<put> will return the record number of the
1188 inserted line via that parameter.
1189
1190 =back
1191
1192 =head1 THE API INTERFACE
1193
1194 As well as accessing Berkeley DB using a tied hash or array, it is also
1195 possible to make direct use of most of the API functions defined in the
1196 Berkeley DB documentation.
1197
1198 To do this you need to store a copy of the object returned from the tie.
1199
1200         $db = tie %hash, "DB_File", "filename" ;
1201
1202 Once you have done that, you can access the Berkeley DB API functions
1203 as B<DB_File> methods directly like this:
1204
1205         $db->put($key, $value, R_NOOVERWRITE) ;
1206
1207 B<Important:> If you have saved a copy of the object returned from
1208 C<tie>, the underlying database file will I<not> be closed until both
1209 the tied variable is untied and all copies of the saved object are
1210 destroyed. 
1211
1212     use DB_File ;
1213     $db = tie %hash, "DB_File", "filename" 
1214         or die "Cannot tie filename: $!" ;
1215     ...
1216     undef $db ;
1217     untie %hash ;
1218
1219 See L<The untie() Gotcha> for more details.
1220
1221 All the functions defined in L<dbopen> are available except for
1222 close() and dbopen() itself. The B<DB_File> method interface to the
1223 supported functions have been implemented to mirror the way Berkeley DB
1224 works whenever possible. In particular note that:
1225
1226 =over 5
1227
1228 =item *
1229
1230 The methods return a status value. All return 0 on success.
1231 All return -1 to signify an error and set C<$!> to the exact
1232 error code. The return code 1 generally (but not always) means that the
1233 key specified did not exist in the database.
1234
1235 Other return codes are defined. See below and in the Berkeley DB
1236 documentation for details. The Berkeley DB documentation should be used
1237 as the definitive source.
1238
1239 =item *
1240
1241 Whenever a Berkeley DB function returns data via one of its parameters,
1242 the equivalent B<DB_File> method does exactly the same.
1243
1244 =item *
1245
1246 If you are careful, it is possible to mix API calls with the tied
1247 hash/array interface in the same piece of code. Although only a few of
1248 the methods used to implement the tied interface currently make use of
1249 the cursor, you should always assume that the cursor has been changed
1250 any time the tied hash/array interface is used. As an example, this
1251 code will probably not do what you expect:
1252
1253     $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1254         or die "Cannot tie $filename: $!" ;
1255
1256     # Get the first key/value pair and set  the cursor
1257     $X->seq($key, $value, R_FIRST) ;
1258
1259     # this line will modify the cursor
1260     $count = scalar keys %x ; 
1261
1262     # Get the second key/value pair.
1263     # oops, it didn't, it got the last key/value pair!
1264     $X->seq($key, $value, R_NEXT) ;
1265
1266 The code above can be rearranged to get around the problem, like this:
1267
1268     $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1269         or die "Cannot tie $filename: $!" ;
1270
1271     # this line will modify the cursor
1272     $count = scalar keys %x ; 
1273
1274     # Get the first key/value pair and set  the cursor
1275     $X->seq($key, $value, R_FIRST) ;
1276
1277     # Get the second key/value pair.
1278     # worked this time.
1279     $X->seq($key, $value, R_NEXT) ;
1280
1281 =back
1282
1283 All the constants defined in L<dbopen> for use in the flags parameters
1284 in the methods defined below are also available. Refer to the Berkeley
1285 DB documentation for the precise meaning of the flags values.
1286
1287 Below is a list of the methods available.
1288
1289 =over 5
1290
1291 =item B<$status = $X-E<gt>get($key, $value [, $flags]) ;>
1292
1293 Given a key (C<$key>) this method reads the value associated with it
1294 from the database. The value read from the database is returned in the
1295 C<$value> parameter.
1296
1297 If the key does not exist the method returns 1.
1298
1299 No flags are currently defined for this method.
1300
1301 =item B<$status = $X-E<gt>put($key, $value [, $flags]) ;>
1302
1303 Stores the key/value pair in the database.
1304
1305 If you use either the R_IAFTER or R_IBEFORE flags, the C<$key> parameter
1306 will have the record number of the inserted key/value pair set.
1307
1308 Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
1309 R_SETCURSOR.
1310
1311 =item B<$status = $X-E<gt>del($key [, $flags]) ;>
1312
1313 Removes all key/value pairs with key C<$key> from the database.
1314
1315 A return code of 1 means that the requested key was not in the
1316 database.
1317
1318 R_CURSOR is the only valid flag at present.
1319
1320 =item B<$status = $X-E<gt>fd ;>
1321
1322 Returns the file descriptor for the underlying database.
1323
1324 See L<Locking Databases> for an example of how to make use of the
1325 C<fd> method to lock your database.
1326
1327 =item B<$status = $X-E<gt>seq($key, $value, $flags) ;>
1328
1329 This interface allows sequential retrieval from the database. See
1330 L<dbopen> for full details.
1331
1332 Both the C<$key> and C<$value> parameters will be set to the key/value
1333 pair read from the database.
1334
1335 The flags parameter is mandatory. The valid flag values are R_CURSOR,
1336 R_FIRST, R_LAST, R_NEXT and R_PREV.
1337
1338 =item B<$status = $X-E<gt>sync([$flags]) ;>
1339
1340 Flushes any cached buffers to disk.
1341
1342 R_RECNOSYNC is the only valid flag at present.
1343
1344 =back
1345
1346 =head1 HINTS AND TIPS 
1347
1348
1349 =head2 Locking Databases
1350
1351 Concurrent access of a read-write database by several parties requires
1352 them all to use some kind of locking.  Here's an example of Tom's that
1353 uses the I<fd> method to get the file descriptor, and then a careful
1354 open() to give something Perl will flock() for you.  Run this repeatedly
1355 in the background to watch the locks granted in proper order.
1356
1357     use DB_File;
1358
1359     use strict;
1360
1361     sub LOCK_SH { 1 }
1362     sub LOCK_EX { 2 }
1363     sub LOCK_NB { 4 }
1364     sub LOCK_UN { 8 }
1365
1366     my($oldval, $fd, $db, %db, $value, $key);
1367
1368     $key = shift || 'default';
1369     $value = shift || 'magic';
1370
1371     $value .= " $$";
1372
1373     $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0644) 
1374             || die "dbcreat /tmp/foo.db $!";
1375     $fd = $db->fd;
1376     print "$$: db fd is $fd\n";
1377     open(DB_FH, "+<&=$fd") || die "dup $!";
1378
1379
1380     unless (flock (DB_FH, LOCK_SH | LOCK_NB)) {
1381         print "$$: CONTENTION; can't read during write update!
1382                     Waiting for read lock ($!) ....";
1383         unless (flock (DB_FH, LOCK_SH)) { die "flock: $!" }
1384     } 
1385     print "$$: Read lock granted\n";
1386
1387     $oldval = $db{$key};
1388     print "$$: Old value was $oldval\n";
1389     flock(DB_FH, LOCK_UN);
1390
1391     unless (flock (DB_FH, LOCK_EX | LOCK_NB)) {
1392         print "$$: CONTENTION; must have exclusive lock!
1393                     Waiting for write lock ($!) ....";
1394         unless (flock (DB_FH, LOCK_EX)) { die "flock: $!" }
1395     } 
1396
1397     print "$$: Write lock granted\n";
1398     $db{$key} = $value;
1399     $db->sync;  # to flush
1400     sleep 10;
1401
1402     flock(DB_FH, LOCK_UN);
1403     undef $db;
1404     untie %db;
1405     close(DB_FH);
1406     print "$$: Updated db to $key=$value\n";
1407
1408 =head2 Sharing Databases With C Applications
1409
1410 There is no technical reason why a Berkeley DB database cannot be
1411 shared by both a Perl and a C application.
1412
1413 The vast majority of problems that are reported in this area boil down
1414 to the fact that C strings are NULL terminated, whilst Perl strings are
1415 not. 
1416
1417 Here is a real example. Netscape 2.0 keeps a record of the locations you
1418 visit along with the time you last visited them in a DB_HASH database.
1419 This is usually stored in the file F<~/.netscape/history.db>. The key
1420 field in the database is the location string and the value field is the
1421 time the location was last visited stored as a 4 byte binary value.
1422
1423 If you haven't already guessed, the location string is stored with a
1424 terminating NULL. This means you need to be careful when accessing the
1425 database.
1426
1427 Here is a snippet of code that is loosely based on Tom Christiansen's
1428 I<ggh> script (available from your nearest CPAN archive in
1429 F<authors/id/TOMC/scripts/nshist.gz>).
1430
1431     use strict ;
1432     use DB_File ;
1433     use Fcntl ;
1434
1435     use vars qw( $dotdir $HISTORY %hist_db $href $binary_time $date ) ;
1436     $dotdir = $ENV{HOME} || $ENV{LOGNAME};
1437
1438     $HISTORY = "$dotdir/.netscape/history.db";
1439
1440     tie %hist_db, 'DB_File', $HISTORY
1441         or die "Cannot open $HISTORY: $!\n" ;;
1442
1443     # Dump the complete database
1444     while ( ($href, $binary_time) = each %hist_db ) {
1445
1446         # remove the terminating NULL
1447         $href =~ s/\x00$// ;
1448
1449         # convert the binary time into a user friendly string
1450         $date = localtime unpack("V", $binary_time);
1451         print "$date $href\n" ;
1452     }
1453
1454     # check for the existence of a specific key
1455     # remember to add the NULL
1456     if ( $binary_time = $hist_db{"http://mox.perl.com/\x00"} ) {
1457         $date = localtime unpack("V", $binary_time) ;
1458         print "Last visited mox.perl.com on $date\n" ;
1459     }
1460     else {
1461         print "Never visited mox.perl.com\n"
1462     }
1463
1464     untie %hist_db ;
1465
1466 =head2 The untie() Gotcha
1467
1468 If you make use of the Berkeley DB API, it is I<very> strongly
1469 recommended that you read L<perltie/The untie Gotcha>. 
1470
1471 Even if you don't currently make use of the API interface, it is still
1472 worth reading it.
1473
1474 Here is an example which illustrates the problem from a B<DB_File>
1475 perspective:
1476
1477     use DB_File ;
1478     use Fcntl ;
1479
1480     my %x ;
1481     my $X ;
1482
1483     $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
1484         or die "Cannot tie first time: $!" ;
1485
1486     $x{123} = 456 ;
1487
1488     untie %x ;
1489
1490     tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1491         or die "Cannot tie second time: $!" ;
1492
1493     untie %x ;
1494
1495 When run, the script will produce this error message:
1496
1497     Cannot tie second time: Invalid argument at bad.file line 14.
1498
1499 Although the error message above refers to the second tie() statement
1500 in the script, the source of the problem is really with the untie()
1501 statement that precedes it.
1502
1503 Having read L<perltie> you will probably have already guessed that the
1504 error is caused by the extra copy of the tied object stored in C<$X>.
1505 If you haven't, then the problem boils down to the fact that the
1506 B<DB_File> destructor, DESTROY, will not be called until I<all>
1507 references to the tied object are destroyed. Both the tied variable,
1508 C<%x>, and C<$X> above hold a reference to the object. The call to
1509 untie() will destroy the first, but C<$X> still holds a valid
1510 reference, so the destructor will not get called and the database file
1511 F<tst.fil> will remain open. The fact that Berkeley DB then reports the
1512 attempt to open a database that is alreday open via the catch-all
1513 "Invalid argument" doesn't help.
1514
1515 If you run the script with the C<-w> flag the error message becomes:
1516
1517     untie attempted while 1 inner references still exist at bad.file line 12.
1518     Cannot tie second time: Invalid argument at bad.file line 14.
1519
1520 which pinpoints the real problem. Finally the script can now be
1521 modified to fix the original problem by destroying the API object
1522 before the untie:
1523
1524     ...
1525     $x{123} = 456 ;
1526
1527     undef $X ;
1528     untie %x ;
1529
1530     $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1531     ...
1532
1533
1534 =head1 COMMON QUESTIONS
1535
1536 =head2 Why is there Perl source in my database?
1537
1538 If you look at the contents of a database file created by DB_File,
1539 there can sometimes be part of a Perl script included in it.
1540
1541 This happens because Berkeley DB uses dynamic memory to allocate
1542 buffers which will subsequently be written to the database file. Being
1543 dynamic, the memory could have been used for anything before DB
1544 malloced it. As Berkeley DB doesn't clear the memory once it has been
1545 allocated, the unused portions will contain random junk. In the case
1546 where a Perl script gets written to the database, the random junk will
1547 correspond to an area of dynamic memory that happened to be used during
1548 the compilation of the script.
1549
1550 Unless you don't like the possibility of there being part of your Perl
1551 scripts embedded in a database file, this is nothing to worry about.
1552
1553 =head2 How do I store complex data structures with DB_File?
1554
1555 Although B<DB_File> cannot do this directly, there is a module which
1556 can layer transparently over B<DB_File> to accomplish this feat.
1557
1558 Check out the MLDBM module, available on CPAN in the directory
1559 F<modules/by-module/MLDBM>.
1560
1561 =head2 What does "Invalid Argument" mean?
1562
1563 You will get this error message when one of the parameters in the
1564 C<tie> call is wrong. Unfortunately there are quite a few parameters to
1565 get wrong, so it can be difficult to figure out which one it is.
1566
1567 Here are a couple of possibilities:
1568
1569 =over 5
1570
1571 =item 1.
1572
1573 Attempting to reopen a database without closing it. 
1574
1575 =item 2.
1576
1577 Using the O_WRONLY flag.
1578
1579 =back
1580
1581 =head2 What does "Bareword 'DB_File' not allowed" mean? 
1582
1583 You will encounter this particular error message when you have the
1584 C<strict 'subs'> pragma (or the full strict pragma) in your script.
1585 Consider this script:
1586
1587     use strict ;
1588     use DB_File ;
1589     use vars qw(%x) ;
1590     tie %x, DB_File, "filename" ;
1591
1592 Running it produces the error in question:
1593
1594     Bareword "DB_File" not allowed while "strict subs" in use 
1595
1596 To get around the error, place the word C<DB_File> in either single or
1597 double quotes, like this:
1598
1599     tie %x, "DB_File", "filename" ;
1600
1601 Although it might seem like a real pain, it is really worth the effort
1602 of having a C<use strict> in all your scripts.
1603
1604 =head1 HISTORY
1605
1606 Moved to the Changes file.
1607
1608 =head1 BUGS
1609
1610 Some older versions of Berkeley DB had problems with fixed length
1611 records using the RECNO file format. This problem has been fixed since
1612 version 1.85 of Berkeley DB.
1613
1614 I am sure there are bugs in the code. If you do find any, or can
1615 suggest any enhancements, I would welcome your comments.
1616
1617 =head1 AVAILABILITY
1618
1619 B<DB_File> comes with the standard Perl source distribution. Look in
1620 the directory F<ext/DB_File>. Given the amount of time between releases
1621 of Perl the version that ships with Perl is quite likely to be out of
1622 date, so the most recent version can always be found on CPAN (see
1623 L<perlmod/CPAN> for details), in the directory
1624 F<modules/by-module/DB_File>.
1625
1626 This version of B<DB_File> will work with either version 1.x or 2.x of
1627 Berkeley DB, but is limited to the functionality provided by version 1.
1628
1629 The official web site for Berkeley DB is
1630 F<http://www.sleepycat.com/db>. The ftp equivalent is
1631 F<ftp.sleepycat.com:/pub>. Both versions 1 and 2 of Berkeley DB are
1632 available there.
1633
1634 Alternatively, Berkeley DB version 1 is available at your nearest CPAN
1635 archive in F<src/misc/db.1.85.tar.gz>.
1636
1637 If you are running IRIX, then get Berkeley DB version 1 from
1638 F<http://reality.sgi.com/ariel>. It has the patches necessary to
1639 compile properly on IRIX 5.3.
1640
1641 =head1 COPYRIGHT
1642
1643 Copyright (c) 1997 Paul Marquess. All rights reserved. This program is
1644 free software; you can redistribute it and/or modify it under the same
1645 terms as Perl itself.
1646
1647 Although B<DB_File> is covered by the Perl license, the library it
1648 makes use of, namely Berkeley DB, is not. Berkeley DB has its own
1649 copyright and its own license. Please take the time to read it.
1650
1651 The license for Berkeley DB version 2, and how it relates to DB_File
1652 does need some extra clarification. Here are are few words taken from
1653 the Berkeley DB FAQ regarding the version 2 license:
1654
1655     The major difference is that the license for DB 2.0, when
1656     downloaded from the net, requires that the software that
1657     uses DB 2.0 be freely redistributable.
1658
1659 That means that if you want to use DB_File, and you have changed either
1660 the source for Berkeley DB or Perl, then the changes must be freely
1661 available.
1662
1663 In the case of Perl, the term source refers to the complete source
1664 code for Perl (e.g. sv.c, toke.c, perl.h) and any external modules that
1665 you are using (e.g. DB_File, Tk).
1666
1667 Note that any Perl scripts that you write are your property - this
1668 includes scripts that make use of DB_File. Neither the Perl license or
1669 the Berkeley DB license place any restriction on what you have to do
1670 with them.
1671
1672 If you are in any doubt about the license situation, contact either the
1673 Berkeley DB authors or the author of DB_File. See L<"AUTHOR"> for details.
1674
1675
1676 =head1 SEE ALSO
1677
1678 L<perl(1)>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)> 
1679
1680 =head1 AUTHOR
1681
1682 The DB_File interface was written by Paul Marquess
1683 E<lt>pmarquess@bfsec.bt.co.ukE<gt>.
1684 Questions about the DB system itself may be addressed to
1685 E<lt>db@sleepycat.com<gt>.
1686
1687 =cut