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