home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _5772d4263bf8bd109965ef47a89b92d2 < prev    next >
Text File  |  2000-03-23  |  65KB  |  1,589 lines

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