DB_File.pm
上传用户:tsgydb
上传日期:2007-04-14
资源大小:10674k
文件大小:56k
源码类别:

MySQL数据库

开发平台:

Visual C++

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