{
    "mode": "man",
    "parameter": "DB_File",
    "section": "3",
    "url": "https://www.chedong.com/phpMan.php/man/DB_File/3/json",
    "generated": "2026-10-22T12:51:56Z",
    "synopsis": "use DBFile;\n[$X =] tie %hash,  'DBFile', [$filename, $flags, $mode, $DBHASH] ;\n[$X =] tie %hash,  'DBFile', $filename, $flags, $mode, $DBBTREE ;\n[$X =] tie @array, 'DBFile', $filename, $flags, $mode, $DBRECNO ;\n$status = $X->del($key [, $flags]) ;\n$status = $X->put($key, $value [, $flags]) ;\n$status = $X->get($key, $value [, $flags]) ;\n$status = $X->seq($key, $value, $flags) ;\n$status = $X->sync([$flags]) ;\n$status = $X->fd ;\n# BTREE only\n$count = $X->getdup($key) ;\n@list  = $X->getdup($key) ;\n%list  = $X->getdup($key, 1) ;\n$status = $X->finddup($key, $value) ;\n$status = $X->deldup($key, $value) ;\n# RECNO only\n$a = $X->length;\n$a = $X->pop ;\n$X->push(list);\n$a = $X->shift;\n$X->unshift(list);\n@r = $X->splice(offset, length, elements);\n# DBM Filters\n$oldfilter = $db->filterstorekey  ( sub { ... } ) ;\n$oldfilter = $db->filterstorevalue( sub { ... } ) ;\n$oldfilter = $db->filterfetchkey  ( sub { ... } ) ;\n$oldfilter = $db->filterfetchvalue( sub { ... } ) ;\nuntie %hash ;\nuntie @array ;",
    "sections": {
        "NAME": {
            "content": "DBFile - Perl5 access to Berkeley DB version 1.x\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use DBFile;\n\n[$X =] tie %hash,  'DBFile', [$filename, $flags, $mode, $DBHASH] ;\n[$X =] tie %hash,  'DBFile', $filename, $flags, $mode, $DBBTREE ;\n[$X =] tie @array, 'DBFile', $filename, $flags, $mode, $DBRECNO ;\n\n$status = $X->del($key [, $flags]) ;\n$status = $X->put($key, $value [, $flags]) ;\n$status = $X->get($key, $value [, $flags]) ;\n$status = $X->seq($key, $value, $flags) ;\n$status = $X->sync([$flags]) ;\n$status = $X->fd ;\n\n# BTREE only\n$count = $X->getdup($key) ;\n@list  = $X->getdup($key) ;\n%list  = $X->getdup($key, 1) ;\n$status = $X->finddup($key, $value) ;\n$status = $X->deldup($key, $value) ;\n\n# RECNO only\n$a = $X->length;\n$a = $X->pop ;\n$X->push(list);\n$a = $X->shift;\n$X->unshift(list);\n@r = $X->splice(offset, length, elements);\n\n# DBM Filters\n$oldfilter = $db->filterstorekey  ( sub { ... } ) ;\n$oldfilter = $db->filterstorevalue( sub { ... } ) ;\n$oldfilter = $db->filterfetchkey  ( sub { ... } ) ;\n$oldfilter = $db->filterfetchvalue( sub { ... } ) ;\n\nuntie %hash ;\nuntie @array ;\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "DBFile is a module which allows Perl programs to make use of the facilities provided by\nBerkeley DB version 1.x (if you have a newer version of DB, see \"Using DBFile with Berkeley\nDB version 2 or greater\").  It is assumed that you have a copy of the Berkeley DB manual\npages at hand when reading this documentation. The interface defined here mirrors the\nBerkeley DB interface closely.\n\nBerkeley DB is a C library which provides a consistent interface to a number of database\nformats.  DBFile provides an interface to all three of the database types currently\nsupported by Berkeley DB.\n\nThe file types are:\n\nDBHASH\nThis  database type allows arbitrary key/value pairs to be stored in data files. This is\nequivalent to the functionality provided by other hashing packages like DBM, NDBM, ODBM,\nGDBM, and SDBM. Remember though, the files created using DBHASH are not compatible with\nany of the other packages mentioned.\n\nA default hashing algorithm, which will be adequate for most applications, is built into\nBerkeley DB. If you do need to use your own hashing algorithm it is  possible  to  write\nyour own in Perl and have DBFile use it instead.\n\nDBBTREE\nThe  btree  format  allows  arbitrary key/value pairs to be stored in a sorted, balanced\nbinary tree.\n\nAs with the DBHASH format, it is possible to provide a user  defined  Perl  routine  to\nperform  the  comparison  of  keys.  By  default, though, the keys are stored in lexical\norder.\n\nDBRECNO\nDBRECNO allows both fixed-length and variable-length flat text files to be  manipulated\nusing  the  same  key/value pair interface as in DBHASH and DBBTREE.  In this case the\nkey will consist of a record (line) number.\n",
            "subsections": [
                {
                    "name": "Using DB_File with Berkeley DB version 2 or greater",
                    "content": "Although DBFile is intended to be used with Berkeley DB version 1, it can also be used  with\nversion  2,  3  or  4. In this case the interface is limited to the functionality provided by\nBerkeley DB 1.x. Anywhere the version 2 or greater interface differs, DBFile arranges for it\nto work like version 1. This feature allows DBFile scripts that were built with version 1 to\nbe migrated to version 2 or greater without any changes.\n\nIf you want to make use of the new features available in Berkeley DB 2.x or greater, use  the\nPerl module BerkeleyDB <https://metacpan.org/pod/BerkeleyDB> instead.\n\nNote:  The database file format has changed multiple times in Berkeley DB version 2, 3 and 4.\nIf you cannot recreate your databases, you must dump any existing databases with  either  the\n\"dbdump\"  or  the  \"dbdump185\"  utility that comes with Berkeley DB.  Once you have rebuilt\nDBFile to use Berkeley DB version 2 or  greater,  your  databases  can  be  recreated  using\n\"dbload\". Refer to the Berkeley DB documentation for further details.\n\nPlease read \"COPYRIGHT\" before using version 2.x or greater of Berkeley DB with DBFile.\n"
                },
                {
                    "name": "Interface to Berkeley DB",
                    "content": "DBFile  allows  access  to  Berkeley  DB files using the tie() mechanism in Perl 5 (for full\ndetails, see \"tie()\" in perlfunc). This facility allows DBFile to access Berkeley  DB  files\nusing  either  an  associative array (for DBHASH & DBBTREE file types) or an ordinary array\n(for the DBRECNO file type).\n\nIn addition to the tie() interface, it is also possible  to  access  most  of  the  functions\nprovided in the Berkeley DB API directly.  See \"THE API INTERFACE\".\n"
                },
                {
                    "name": "Opening a Berkeley DB Database File",
                    "content": "Berkeley DB uses the function dbopen() to open or create a database.  Here is the C prototype\nfor dbopen():\n\nDB*\ndbopen (const char * file, int flags, int mode,\nDBTYPE type, const void * openinfo)\n\nThe  parameter  \"type\"  is  an  enumeration  which specifies which of the 3 interface methods\n(DBHASH, DBBTREE or DBRECNO) is to be used.  Depending  on  which  of  these  is  actually\nchosen,  the  final  parameter, openinfo points to a data structure which allows tailoring of\nthe specific interface method.\n\nThis interface is handled slightly differently in DBFile. Here is an equivalent  call  using\nDBFile:\n\ntie %array, 'DBFile', $filename, $flags, $mode, $DBHASH ;\n\nThe  \"filename\",  \"flags\"  and  \"mode\" parameters are the direct equivalent of their dbopen()\ncounterparts. The final parameter $DBHASH performs the  function  of  both  the  \"type\"  and\n\"openinfo\" parameters in dbopen().\n\nIn  the  example above $DBHASH is actually a pre-defined reference to a hash object. DBFile\nhas three of these pre-defined references.  Apart from $DBHASH, there is also $DBBTREE  and\n$DBRECNO.\n\nThe  keys allowed in each of these pre-defined references is limited to the names used in the\nequivalent C structure. So, for example, the $DBHASH reference will only allow  keys  called\n\"bsize\", \"cachesize\", \"ffactor\", \"hash\", \"lorder\" and \"nelem\".\n\nTo change one of these elements, just assign to it like this:\n\n$DBHASH->{'cachesize'} = 10000 ;\n\nThe  three  predefined  variables  $DBHASH, $DBBTREE and $DBRECNO are usually adequate for\nmost applications.  If you do need to create extra instances of these  objects,  constructors\nare available for each file type.\n\nHere  are  examples of the constructors and the valid options available for DBHASH, DBBTREE\nand DBRECNO respectively.\n\n$a = DBFile::HASHINFO->new();\n$a->{'bsize'} ;\n$a->{'cachesize'} ;\n$a->{'ffactor'};\n$a->{'hash'} ;\n$a->{'lorder'} ;\n$a->{'nelem'} ;\n\n$b = DBFile::BTREEINFO->new();\n$b->{'flags'} ;\n$b->{'cachesize'} ;\n$b->{'maxkeypage'} ;\n$b->{'minkeypage'} ;\n$b->{'psize'} ;\n$b->{'compare'} ;\n$b->{'prefix'} ;\n$b->{'lorder'} ;\n\n$c = DBFile::RECNOINFO->new();\n$c->{'bval'} ;\n$c->{'cachesize'} ;\n$c->{'psize'} ;\n$c->{'flags'} ;\n$c->{'lorder'} ;\n$c->{'reclen'} ;\n$c->{'bfname'} ;\n\nThe values stored  in  the  hashes  above  are  mostly  the  direct  equivalent  of  their  C\ncounterpart.  Like  their  C  counterparts,  all are set to a default values - that means you\ndon't have to set all of the values when you only want to change one. Here is an example:\n\n$a = DBFile::HASHINFO->new();\n$a->{'cachesize'} =  12345 ;\ntie %y, 'DBFile', \"filename\", $flags, 0777, $a ;\n\nA few of the options need extra discussion here. When used, the  C  equivalent  of  the  keys\n\"hash\",  \"compare\" and \"prefix\" store pointers to C functions. In DBFile these keys are used\nto store references to Perl subs. Below are templates for each of the subs:\n\nsub hash\n{\nmy ($data) = @ ;\n...\n# return the hash value for $data\nreturn $hash ;\n}\n\nsub compare\n{\nmy ($key, $key2) = @ ;\n...\n# return  0 if $key1 eq $key2\n#        -1 if $key1 lt $key2\n#         1 if $key1 gt $key2\nreturn (-1 , 0 or 1) ;\n}\n\nsub prefix\n{\nmy ($key, $key2) = @ ;\n...\n# return number of bytes of $key2 which are\n# necessary to determine that it is greater than $key1\nreturn $bytes ;\n}\n\nSee \"Changing the BTREE sort order\" for an example of using the \"compare\" template.\n\nIf you are using the DBRECNO interface and you intend making use of \"bval\", you should check\nout \"The 'bval' Option\".\n"
                },
                {
                    "name": "Default Parameters",
                    "content": "It is possible to omit some or all of the final 4 parameters in the call  to  \"tie\"  and  let\nthem take default values. As DBHASH is the most common file format used, the call:\n\ntie %A, \"DBFile\", \"filename\" ;\n\nis equivalent to:\n\ntie %A, \"DBFile\", \"filename\", OCREAT|ORDWR, 0666, $DBHASH ;\n\nIt is also possible to omit the filename parameter as well, so the call:\n\ntie %A, \"DBFile\" ;\n\nis equivalent to:\n\ntie %A, \"DBFile\", undef, OCREAT|ORDWR, 0666, $DBHASH ;\n\nSee \"In Memory Databases\" for a discussion on the use of \"undef\" in place of a filename.\n"
                },
                {
                    "name": "In Memory Databases",
                    "content": "Berkeley  DB allows the creation of in-memory databases by using NULL (that is, a \"(char *)0\"\nin C) in place of the filename.  DBFile  uses  \"undef\"  instead  of  NULL  to  provide  this\nfunctionality.\n"
                }
            ]
        },
        "DBHASH": {
            "content": "The  DBHASH  file  format  is probably the most commonly used of the three file formats that\nDBFile supports. It is also very straightforward to use.\n",
            "subsections": [
                {
                    "name": "A Simple Example",
                    "content": "This example shows how to create a database, add key/value  pairs  to  the  database,  delete\nkeys/value pairs and finally how to enumerate the contents of the database.\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\nour (%h, $k, $v) ;\n\nunlink \"fruit\" ;\ntie %h, \"DBFile\", \"fruit\", ORDWR|OCREAT, 0666, $DBHASH\nor die \"Cannot open file 'fruit': $!\\n\";\n\n# Add a few key/value pairs to the file\n$h{\"apple\"} = \"red\" ;\n$h{\"orange\"} = \"orange\" ;\n$h{\"banana\"} = \"yellow\" ;\n$h{\"tomato\"} = \"red\" ;\n\n# Check for existence of a key\nprint \"Banana Exists\\n\\n\" if $h{\"banana\"} ;\n\n# Delete a key/value pair.\ndelete $h{\"apple\"} ;\n\n# print the contents of the file\nwhile (($k, $v) = each %h)\n{ print \"$k -> $v\\n\" }\n\nuntie %h ;\n\nhere is the output:\n\nBanana Exists\n\norange -> orange\ntomato -> red\nbanana -> yellow\n\nNote  that  the  like  ordinary  associative arrays, the order of the keys retrieved is in an\napparently random order.\n"
                }
            ]
        },
        "DBBTREE": {
            "content": "The DBBTREE format is useful when you want to store data in a given order.  By  default  the\nkeys  will be stored in lexical order, but as you will see from the example shown in the next\nsection, it is very easy to define your own sorting function.\n",
            "subsections": [
                {
                    "name": "Changing the BTREE sort order",
                    "content": "This script shows how to override the default sorting algorithm that BTREE uses.  Instead  of\nusing the normal lexical ordering, a case insensitive compare function will be used.\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\n\nmy %h ;\n\nsub Compare\n{\nmy ($key1, $key2) = @ ;\n\"\\L$key1\" cmp \"\\L$key2\" ;\n}\n\n# specify the Perl sub that will do the comparison\n$DBBTREE->{'compare'} = \\&Compare ;\n\nunlink \"tree\" ;\ntie %h, \"DBFile\", \"tree\", ORDWR|OCREAT, 0666, $DBBTREE\nor die \"Cannot open file 'tree': $!\\n\" ;\n\n# Add a key/value pair to the file\n$h{'Wall'} = 'Larry' ;\n$h{'Smith'} = 'John' ;\n$h{'mouse'} = 'mickey' ;\n$h{'duck'}  = 'donald' ;\n\n# Delete\ndelete $h{\"duck\"} ;\n\n# Cycle through the keys printing them in order.\n# Note it is not necessary to sort the keys as\n# the btree will have kept them in order automatically.\nforeach (keys %h)\n{ print \"$\\n\" }\n\nuntie %h ;\n\nHere is the output from the code above.\n\nmouse\nSmith\nWall\n\nThere are a few point to bear in mind if you want to change the ordering in a BTREE database:\n\n1.   The new compare function must be specified when you create the database.\n\n2.   You cannot change the ordering once the database has been created. Thus you must use the\nsame compare function every time you access the database.\n\n3.   Duplicate keys are entirely defined by the comparison function.  In the case-insensitive\nexample  above,  the keys: 'KEY' and 'key' would be considered duplicates, and assigning\nto the second one would overwrite the first. If duplicates are  allowed  for  (with  the\nRDUP  flag  discussed  below),  only  a  single copy of duplicate keys is stored in the\ndatabase --- so (again with example above) assigning three values to  the  keys:  'KEY',\n'Key',  and  'key'  would  leave  just  the  first key: 'KEY' in the database with three\nvalues. For some situations this results in information loss, so care should be taken to\nprovide fully qualified comparison functions when necessary.   For  example,  the  above\ncomparison  routine  could  be  modified to additionally compare case-sensitively if two\nkeys are equal in the case insensitive comparison:\n\nsub compare {\nmy($key1, $key2) = @;\nlc $key1 cmp lc $key2 ||\n$key1 cmp $key2;\n}\n\nAnd now you will only have duplicates when the  keys  themselves  are  truly  the  same.\n(note:  in  versions of the db library prior to about November 1996, such duplicate keys\nwere retained so it was possible to recover the original  keys  in  sets  of  keys  that\ncompared as equal).\n"
                },
                {
                    "name": "Handling Duplicate Keys",
                    "content": "The  BTREE file type optionally allows a single key to be associated with an arbitrary number\nof values. This option is enabled by setting the flags element of  $DBBTREE  to  RDUP  when\ncreating the database.\n\nThere  are  some  difficulties  in  using the tied hash interface if you want to manipulate a\nBTREE database with duplicate keys. Consider this code:\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\n\nmy ($filename, %h) ;\n\n$filename = \"tree\" ;\nunlink $filename ;\n\n# Enable duplicate records\n$DBBTREE->{'flags'} = RDUP ;\n\ntie %h, \"DBFile\", $filename, ORDWR|OCREAT, 0666, $DBBTREE\nor die \"Cannot open $filename: $!\\n\";\n\n# Add some key/value pairs to the file\n$h{'Wall'} = 'Larry' ;\n$h{'Wall'} = 'Brick' ; # Note the duplicate key\n$h{'Wall'} = 'Brick' ; # Note the duplicate key and value\n$h{'Smith'} = 'John' ;\n$h{'mouse'} = 'mickey' ;\n\n# iterate through the associative array\n# and print each key/value pair.\nforeach (sort keys %h)\n{ print \"$  -> $h{$}\\n\" }\n\nuntie %h ;\n\nHere is the output:\n\nSmith   -> John\nWall    -> Larry\nWall    -> Larry\nWall    -> Larry\nmouse   -> mickey\n\nAs you can see 3 records have been successfully created with key \"Wall\" - the only thing  is,\nwhen  they  are retrieved from the database they seem to have the same value, namely \"Larry\".\nThe problem is caused by the way that the associative array interface works. Basically,  when\nthe  associative  array  interface is used to fetch the value associated with a given key, it\nwill only ever retrieve the first value.\n\nAlthough it may not be immediately  obvious  from  the  code  above,  the  associative  array\ninterface can be used to write values with duplicate keys, but it cannot be used to read them\nback from the database.\n\nThe  way  to get around this problem is to use the Berkeley DB API method called \"seq\".  This\nmethod allows sequential access to key/value pairs. See \"THE API INTERFACE\"  for  details  of\nboth the \"seq\" method and the API in general.\n\nHere is the script above rewritten using the \"seq\" API method.\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\n\nmy ($filename, $x, %h, $status, $key, $value) ;\n\n$filename = \"tree\" ;\nunlink $filename ;\n\n# Enable duplicate records\n$DBBTREE->{'flags'} = RDUP ;\n\n$x = tie %h, \"DBFile\", $filename, ORDWR|OCREAT, 0666, $DBBTREE\nor die \"Cannot open $filename: $!\\n\";\n\n# Add some key/value pairs to the file\n$h{'Wall'} = 'Larry' ;\n$h{'Wall'} = 'Brick' ; # Note the duplicate key\n$h{'Wall'} = 'Brick' ; # Note the duplicate key and value\n$h{'Smith'} = 'John' ;\n$h{'mouse'} = 'mickey' ;\n\n# iterate through the btree using seq\n# and print each key/value pair.\n$key = $value = 0 ;\nfor ($status = $x->seq($key, $value, RFIRST) ;\n$status == 0 ;\n$status = $x->seq($key, $value, RNEXT) )\n{  print \"$key -> $value\\n\" }\n\nundef $x ;\nuntie %h ;\n\nthat prints:\n\nSmith   -> John\nWall    -> Brick\nWall    -> Brick\nWall    -> Larry\nmouse   -> mickey\n\nThis  time we have got all the key/value pairs, including the multiple values associated with\nthe key \"Wall\".\n\nTo make life easier when dealing with duplicate  keys,  DBFile  comes  with  a  few  utility\nmethods.\n"
                },
                {
                    "name": "The get_dup() Method",
                    "content": "The \"getdup\" method assists in reading duplicate values from BTREE databases. The method can\ntake the following forms:\n\n$count = $x->getdup($key) ;\n@list  = $x->getdup($key) ;\n%list  = $x->getdup($key, 1) ;\n\nIn a scalar context the method returns the number of values associated with the key, $key.\n\nIn  list  context,  it  returns all the values which match $key. Note that the values will be\nreturned in an apparently random order.\n\nIn list context, if the second parameter is present and evaluates TRUE, the method returns an\nassociative array. The keys of the associative array correspond to the values that matched in\nthe BTREE and the values of the array are a count of the  number  of  times  that  particular\nvalue occurred in the BTREE.\n\nSo assuming the database created above, we can use \"getdup\" like this:\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\n\nmy ($filename, $x, %h) ;\n\n$filename = \"tree\" ;\n\n# Enable duplicate records\n$DBBTREE->{'flags'} = RDUP ;\n\n$x = tie %h, \"DBFile\", $filename, ORDWR|OCREAT, 0666, $DBBTREE\nor die \"Cannot open $filename: $!\\n\";\n\nmy $cnt  = $x->getdup(\"Wall\") ;\nprint \"Wall occurred $cnt times\\n\" ;\n\nmy %hash = $x->getdup(\"Wall\", 1) ;\nprint \"Larry is there\\n\" if $hash{'Larry'} ;\nprint \"There are $hash{'Brick'} Brick Walls\\n\" ;\n\nmy @list = sort $x->getdup(\"Wall\") ;\nprint \"Wall =>      [@list]\\n\" ;\n\n@list = $x->getdup(\"Smith\") ;\nprint \"Smith =>     [@list]\\n\" ;\n\n@list = $x->getdup(\"Dog\") ;\nprint \"Dog =>       [@list]\\n\" ;\n\nand it will print:\n\nWall occurred 3 times\nLarry is there\nThere are 2 Brick Walls\nWall =>     [Brick Brick Larry]\nSmith =>    [John]\nDog =>      []\n"
                },
                {
                    "name": "The find_dup() Method",
                    "content": "$status = $X->finddup($key, $value) ;\n\nThis  method  checks  for the existence of a specific key/value pair. If the pair exists, the\ncursor is left pointing to the pair and the method returns 0. Otherwise the method returns  a\nnon-zero value.\n\nAssuming the database from the previous example:\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\n\nmy ($filename, $x, %h, $found) ;\n\n$filename = \"tree\" ;\n\n# Enable duplicate records\n$DBBTREE->{'flags'} = RDUP ;\n\n$x = tie %h, \"DBFile\", $filename, ORDWR|OCREAT, 0666, $DBBTREE\nor die \"Cannot open $filename: $!\\n\";\n\n$found = ( $x->finddup(\"Wall\", \"Larry\") == 0 ? \"\" : \"not\") ;\nprint \"Larry Wall is $found there\\n\" ;\n\n$found = ( $x->finddup(\"Wall\", \"Harry\") == 0 ? \"\" : \"not\") ;\nprint \"Harry Wall is $found there\\n\" ;\n\nundef $x ;\nuntie %h ;\n\nprints this\n\nLarry Wall is  there\nHarry Wall is not there\n"
                },
                {
                    "name": "The del_dup() Method",
                    "content": "$status = $X->deldup($key, $value) ;\n\nThis  method  deletes  a  specific  key/value  pair. It returns 0 if they exist and have been\ndeleted successfully.  Otherwise the method returns a non-zero value.\n\nAgain assuming the existence of the \"tree\" database\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\n\nmy ($filename, $x, %h, $found) ;\n\n$filename = \"tree\" ;\n\n# Enable duplicate records\n$DBBTREE->{'flags'} = RDUP ;\n\n$x = tie %h, \"DBFile\", $filename, ORDWR|OCREAT, 0666, $DBBTREE\nor die \"Cannot open $filename: $!\\n\";\n\n$x->deldup(\"Wall\", \"Larry\") ;\n\n$found = ( $x->finddup(\"Wall\", \"Larry\") == 0 ? \"\" : \"not\") ;\nprint \"Larry Wall is $found there\\n\" ;\n\nundef $x ;\nuntie %h ;\n\nprints this\n\nLarry Wall is not there\n"
                },
                {
                    "name": "Matching Partial Keys",
                    "content": "The BTREE interface has a feature which allows partial keys to be matched. This functionality\nis only available when the \"seq\" method is used along with the RCURSOR flag.\n\n$x->seq($key, $value, RCURSOR) ;\n\nHere is the relevant quote from the dbopen man page where it defines the use of the  RCURSOR\nflag with seq:\n\nNote, for the DBBTREE access method, the returned key is not\nnecessarily an exact match for the specified key. The returned key\nis the smallest key greater than or equal to the specified key,\npermitting partial key matches and range searches.\n\nIn  the  example  script below, the \"match\" sub uses this feature to find and print the first\nmatching key/value pair given a partial key.\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\nuse Fcntl ;\n\nmy ($filename, $x, %h, $st, $key, $value) ;\n\nsub match\n{\nmy $key = shift ;\nmy $value = 0;\nmy $origkey = $key ;\n$x->seq($key, $value, RCURSOR) ;\nprint \"$origkey\\t-> $key\\t-> $value\\n\" ;\n}\n\n$filename = \"tree\" ;\nunlink $filename ;\n\n$x = tie %h, \"DBFile\", $filename, ORDWR|OCREAT, 0666, $DBBTREE\nor die \"Cannot open $filename: $!\\n\";\n\n# Add some key/value pairs to the file\n$h{'mouse'} = 'mickey' ;\n$h{'Wall'} = 'Larry' ;\n$h{'Walls'} = 'Brick' ;\n$h{'Smith'} = 'John' ;\n\n\n$key = $value = 0 ;\nprint \"IN ORDER\\n\" ;\nfor ($st = $x->seq($key, $value, RFIRST) ;\n$st == 0 ;\n$st = $x->seq($key, $value, RNEXT) )\n\n{  print \"$key    -> $value\\n\" }\n\nprint \"\\nPARTIAL MATCH\\n\" ;\n\nmatch \"Wa\" ;\nmatch \"A\" ;\nmatch \"a\" ;\n\nundef $x ;\nuntie %h ;\n\nHere is the output:\n\nIN ORDER\nSmith -> John\nWall  -> Larry\nWalls -> Brick\nmouse -> mickey\n\nPARTIAL MATCH\nWa -> Wall  -> Larry\nA  -> Smith -> John\na  -> mouse -> mickey\n"
                }
            ]
        },
        "DBRECNO": {
            "content": "DBRECNO provides an interface to flat text files. Both variable and fixed length records are\nsupported.\n\nIn order to make RECNO more compatible with Perl, the  array  offset  for  all  RECNO  arrays\nbegins at 0 rather than 1 as in Berkeley DB.\n\nAs  with  normal Perl arrays, a RECNO array can be accessed using negative indexes. The index\n-1 refers to the last element of the array, -2 the second last,  and  so  on.  Attempting  to\naccess an element before the start of the array will raise a fatal run-time error.\n",
            "subsections": [
                {
                    "name": "The 'bval' Option",
                    "content": "The  operation  of  the  bval option warrants some discussion. Here is the definition of bval\nfrom the Berkeley DB 1.85 recno manual page:\n\nThe delimiting byte to be used to mark  the  end  of  a\nrecord for variable-length records, and the pad charac-\nter for fixed-length records.  If no  value  is  speci-\nfied,  newlines  (``\\n'')  are  used to mark the end of\nvariable-length records and  fixed-length  records  are\npadded with spaces.\n\nThe second sentence is wrong. In actual fact bval will only default to \"\\n\" when the openinfo\nparameter in dbopen is NULL. If a non-NULL openinfo parameter is used at all, the value  that\nhappens  to  be  in bval will be used. That means you always have to specify bval when making\nuse of any of the options in the openinfo parameter. This documentation error will  be  fixed\nin the next release of Berkeley DB.\n\nThat  clarifies  the situation with regards Berkeley DB itself. What about DBFile? Well, the\nbehavior defined in the quote above is quite useful, so DBFile conforms to it.\n\nThat means that you can specify other options (e.g. cachesize) and still have bval default to\n\"\\n\" for variable length records, and space for fixed length records.\n\nAlso note that the bval option only allows you to specify a single byte as a delimiter.\n"
                },
                {
                    "name": "A Simple Example",
                    "content": "Here is a simple example that uses RECNO (if you are using a version  of  Perl  earlier  than\n5.00457 this example won't work -- see \"Extra RECNO Methods\" for a workaround).\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\n\nmy $filename = \"text\" ;\nunlink $filename ;\n\nmy @h ;\ntie @h, \"DBFile\", $filename, ORDWR|OCREAT, 0666, $DBRECNO\nor die \"Cannot open file 'text': $!\\n\" ;\n\n# Add a few key/value pairs to the file\n$h[0] = \"orange\" ;\n$h[1] = \"blue\" ;\n$h[2] = \"yellow\" ;\n\npush @h, \"green\", \"black\" ;\n\nmy $elements = scalar @h ;\nprint \"The array contains $elements entries\\n\" ;\n\nmy $last = pop @h ;\nprint \"popped $last\\n\" ;\n\nunshift @h, \"white\" ;\nmy $first = shift @h ;\nprint \"shifted $first\\n\" ;\n\n# Check for existence of a key\nprint \"Element 1 Exists with value $h[1]\\n\" if $h[1] ;\n\n# use a negative index\nprint \"The last element is $h[-1]\\n\" ;\nprint \"The 2nd last element is $h[-2]\\n\" ;\n\nuntie @h ;\n\nHere is the output from the script:\n\nThe array contains 5 entries\npopped black\nshifted white\nElement 1 Exists with value blue\nThe last element is green\nThe 2nd last element is yellow\n"
                },
                {
                    "name": "Extra RECNO Methods",
                    "content": "If  you  are using a version of Perl earlier than 5.00457, the tied array interface is quite\nlimited. In the example script above \"push\", \"pop\", \"shift\",  \"unshift\"  or  determining  the\narray length will not work with a tied array.\n\nTo  make  the  interface  more  useful  for  older  versions of Perl, a number of methods are\nsupplied with DBFile to simulate  the  missing  array  operations.  All  these  methods  are\naccessed via the object returned from the tie call.\n\nHere are the methods:\n"
                },
                {
                    "name": "$X->push(list) ;",
                    "content": "Pushes the elements of \"list\" to the end of the array.\n"
                },
                {
                    "name": "$value = $X->pop ;",
                    "content": "Removes and returns the last element of the array.\n"
                },
                {
                    "name": "$X->shift",
                    "content": "Removes and returns the first element of the array.\n"
                },
                {
                    "name": "$X->unshift(list) ;",
                    "content": "Pushes the elements of \"list\" to the start of the array.\n"
                },
                {
                    "name": "$X->length",
                    "content": "Returns the number of elements in the array.\n"
                },
                {
                    "name": "$X->splice(offset, length, elements);",
                    "content": "Returns a splice of the array.\n"
                },
                {
                    "name": "Another Example",
                    "content": "Here  is  a  more  complete example that makes use of some of the methods described above. It\nalso makes use of the API interface directly (see \"THE API INTERFACE\").\n\nuse warnings ;\nuse strict ;\nmy (@h, $H, $file, $i) ;\nuse DBFile ;\nuse Fcntl ;\n\n$file = \"text\" ;\n\nunlink $file ;\n\n$H = tie @h, \"DBFile\", $file, ORDWR|OCREAT, 0666, $DBRECNO\nor die \"Cannot open file $file: $!\\n\" ;\n\n# first create a text file to play with\n$h[0] = \"zero\" ;\n$h[1] = \"one\" ;\n$h[2] = \"two\" ;\n$h[3] = \"three\" ;\n$h[4] = \"four\" ;\n\n\n# Print the records in order.\n#\n# The length method is needed here because evaluating a tied\n# array in a scalar context does not return the number of\n# elements in the array.\n\nprint \"\\nORIGINAL\\n\" ;\nforeach $i (0 .. $H->length - 1) {\nprint \"$i: $h[$i]\\n\" ;\n}\n\n# use the push & pop methods\n$a = $H->pop ;\n$H->push(\"last\") ;\nprint \"\\nThe last record was [$a]\\n\" ;\n\n# and the shift & unshift methods\n$a = $H->shift ;\n$H->unshift(\"first\") ;\nprint \"The first record was [$a]\\n\" ;\n\n# Use the API to add a new record after record 2.\n$i = 2 ;\n$H->put($i, \"Newbie\", RIAFTER) ;\n\n# and a new record before record 1.\n$i = 1 ;\n$H->put($i, \"New One\", RIBEFORE) ;\n\n# delete record 3\n$H->del(3) ;\n\n# now print the records in reverse order\nprint \"\\nREVERSE\\n\" ;\nfor ($i = $H->length - 1 ; $i >= 0 ; -- $i)\n{ print \"$i: $h[$i]\\n\" }\n\n# same again, but use the API functions instead\nprint \"\\nREVERSE again\\n\" ;\nmy ($s, $k, $v)  = (0, 0, 0) ;\nfor ($s = $H->seq($k, $v, RLAST) ;\n$s == 0 ;\n$s = $H->seq($k, $v, RPREV))\n{ print \"$k: $v\\n\" }\n\nundef $H ;\nuntie @h ;\n\nand this is what it outputs:\n\nORIGINAL\n0: zero\n1: one\n2: two\n3: three\n4: four\n\nThe last record was [four]\nThe first record was [zero]\n\nREVERSE\n5: last\n4: three\n3: Newbie\n2: one\n1: New One\n0: first\n\nREVERSE again\n5: last\n4: three\n3: Newbie\n2: one\n1: New One\n0: first\n\nNotes:\n\n1.   Rather than iterating through the array, @h like this:\n\nforeach $i (@h)\n\nit is necessary to use either this:\n\nforeach $i (0 .. $H->length - 1)\n\nor this:\n\nfor ($a = $H->get($k, $v, RFIRST) ;\n$a == 0 ;\n$a = $H->get($k, $v, RNEXT) )\n\n2.   Notice that both times the \"put\" method was used the record index was specified using  a\nvariable,  $i,  rather  than the literal value itself. This is because \"put\" will return\nthe record number of the inserted line via that parameter.\n"
                }
            ]
        },
        "THE API INTERFACE": {
            "content": "As well as accessing Berkeley DB using a tied hash or array, it  is  also  possible  to  make\ndirect use of most of the API functions defined in the Berkeley DB documentation.\n\nTo do this you need to store a copy of the object returned from the tie.\n\n$db = tie %hash, \"DBFile\", \"filename\" ;\n\nOnce  you  have  done  that,  you can access the Berkeley DB API functions as DBFile methods\ndirectly like this:\n\n$db->put($key, $value, RNOOVERWRITE) ;\n\nImportant: If you have saved a copy  of  the  object  returned  from  \"tie\",  the  underlying\ndatabase file will not be closed until both the tied variable is untied and all copies of the\nsaved object are destroyed.\n\nuse DBFile ;\n$db = tie %hash, \"DBFile\", \"filename\"\nor die \"Cannot tie filename: $!\" ;\n...\nundef $db ;\nuntie %hash ;\n\nSee \"The untie() Gotcha\" for more details.\n\nAll the functions defined in dbopen are available except for close() and dbopen() itself. The\nDBFile  method  interface to the supported functions have been implemented to mirror the way\nBerkeley DB works whenever possible. In particular note that:\n\n•    The methods return a status value. All return 0 on success.  All return -1 to signify an\nerror and set $! to the exact error code. The return code 1 generally (but  not  always)\nmeans that the key specified did not exist in the database.\n\nOther  return  codes  are  defined.  See  below and in the Berkeley DB documentation for\ndetails. The Berkeley DB documentation should be used as the definitive source.\n\n•    Whenever a Berkeley DB function returns data via one of its parameters,  the  equivalent\nDBFile method does exactly the same.\n\n•    If  you  are careful, it is possible to mix API calls with the tied hash/array interface\nin the same piece of code. Although only a few of the methods used to implement the tied\ninterface currently make use of the cursor, you should always assume that the cursor has\nbeen changed any time the tied hash/array interface is used. As an  example,  this  code\nwill probably not do what you expect:\n\n$X = tie %x, 'DBFile', $filename, ORDWR|OCREAT, 0777, $DBBTREE\nor die \"Cannot tie $filename: $!\" ;\n\n# Get the first key/value pair and set  the cursor\n$X->seq($key, $value, RFIRST) ;\n\n# this line will modify the cursor\n$count = scalar keys %x ;\n\n# Get the second key/value pair.\n# oops, it didn't, it got the last key/value pair!\n$X->seq($key, $value, RNEXT) ;\n\nThe code above can be rearranged to get around the problem, like this:\n\n$X = tie %x, 'DBFile', $filename, ORDWR|OCREAT, 0777, $DBBTREE\nor die \"Cannot tie $filename: $!\" ;\n\n# this line will modify the cursor\n$count = scalar keys %x ;\n\n# Get the first key/value pair and set  the cursor\n$X->seq($key, $value, RFIRST) ;\n\n# Get the second key/value pair.\n# worked this time.\n$X->seq($key, $value, RNEXT) ;\n\nAll  the  constants  defined in dbopen for use in the flags parameters in the methods defined\nbelow are also available. Refer to the Berkeley DB documentation for the precise  meaning  of\nthe flags values.\n\nBelow is a list of the methods available.\n",
            "subsections": [
                {
                    "name": "$status = $X->get($key, $value [, $flags]) ;",
                    "content": "Given a key ($key) this method reads the value associated with it from the database. The\nvalue read from the database is returned in the $value parameter.\n\nIf the key does not exist the method returns 1.\n\nNo flags are currently defined for this method.\n"
                },
                {
                    "name": "$status = $X->put($key, $value [, $flags]) ;",
                    "content": "Stores the key/value pair in the database.\n\nIf  you  use  either  the  RIAFTER or RIBEFORE flags, the $key parameter will have the\nrecord number of the inserted key/value pair set.\n\nValid flags are RCURSOR, RIAFTER, RIBEFORE, RNOOVERWRITE and RSETCURSOR.\n"
                },
                {
                    "name": "$status = $X->del($key [, $flags]) ;",
                    "content": "Removes all key/value pairs with key $key from the database.\n\nA return code of 1 means that the requested key was not in the database.\n\nRCURSOR is the only valid flag at present.\n"
                },
                {
                    "name": "$status = $X->fd ;",
                    "content": "Returns the file descriptor for the underlying database.\n\nSee \"Locking: The Trouble with fd\" for an explanation for why you should not use \"fd\" to\nlock your database.\n"
                },
                {
                    "name": "$status = $X->seq($key, $value, $flags) ;",
                    "content": "This interface allows sequential retrieval  from  the  database.  See  dbopen  for  full\ndetails.\n\nBoth  the  $key  and  $value  parameters will be set to the key/value pair read from the\ndatabase.\n\nThe flags parameter is mandatory. The valid flag values are RCURSOR,  RFIRST,  RLAST,\nRNEXT and RPREV.\n"
                },
                {
                    "name": "$status = $X->sync([$flags]) ;",
                    "content": "Flushes any cached buffers to disk.\n\nRRECNOSYNC is the only valid flag at present.\n"
                }
            ]
        },
        "DBM FILTERS": {
            "content": "A  DBM  Filter  is  a  piece  of  code  that is be used when you always want to make the same\ntransformation to all keys and/or values in a DBM database.  An example is when you  need  to\nencode  your  data  in  UTF-8  before  writing to the database and then decode the UTF-8 when\nreading from the database file.\n\nThere are two ways to use a DBM Filter.\n\n1.   Using the low-level API defined below.\n\n2.   Using the DBMFilter module.  This module hides the complexity of the API defined  below\nand comes with a number of \"canned\" filters that cover some of the common use-cases.\n\nUse of the DBMFilter module is recommended.\n",
            "subsections": [
                {
                    "name": "DBM Filter Low-level API",
                    "content": "There are four methods associated with DBM Filters. All work identically, and each is used to\ninstall  (or  uninstall)  a  single  DBM  Filter.  Each  expects a single parameter, namely a\nreference to a sub. The only difference  between  them  is  the  place  that  the  filter  is\ninstalled.\n\nTo summarise:\n"
                },
                {
                    "name": "filter_store_key",
                    "content": "If a filter has been installed with this method, it will be invoked every time you write\na key to a DBM database.\n"
                },
                {
                    "name": "filter_store_value",
                    "content": "If a filter has been installed with this method, it will be invoked every time you write\na value to a DBM database.\n"
                },
                {
                    "name": "filter_fetch_key",
                    "content": "If  a filter has been installed with this method, it will be invoked every time you read\na key from a DBM database.\n"
                },
                {
                    "name": "filter_fetch_value",
                    "content": "If a filter has been installed with this method, it will be invoked every time you  read\na value from a DBM database.\n\nYou can use any combination of the methods, from none, to all four.\n\nAll filter methods return the existing filter, if present, or \"undef\" in not.\n\nTo delete a filter pass \"undef\" to it.\n"
                },
                {
                    "name": "The Filter",
                    "content": "When  each  filter  is called by Perl, a local copy of $ will contain the key or value to be\nfiltered. Filtering is achieved by modifying the contents of $. The  return  code  from  the\nfilter is ignored.\n"
                },
                {
                    "name": "An Example -- the NULL termination problem.",
                    "content": "Consider the following scenario. You have a DBM database that you need to share with a third-\nparty  C application. The C application assumes that all keys and values are NULL terminated.\nUnfortunately when Perl writes to DBM databases it doesn't use NULL termination, so your Perl\napplication will have to manage NULL termination itself. When you write to the  database  you\nwill have to use something like this:\n\n$hash{\"$key\\0\"} = \"$value\\0\" ;\n\nSimilarly  the  NULL  needs  to  be taken into account when you are considering the length of\nexisting keys/values.\n\nIt would be much better if  you  could  ignore  the  NULL  terminations  issue  in  the  main\napplication  code  and  have a mechanism that automatically added the terminating NULL to all\nkeys and values whenever you write to the database and have them removed when you  read  from\nthe  database.  As  I'm sure you have already guessed, this is a problem that DBM Filters can\nfix very easily.\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\n\nmy %hash ;\nmy $filename = \"filt\" ;\nunlink $filename ;\n\nmy $db = tie %hash, 'DBFile', $filename, OCREAT|ORDWR, 0666, $DBHASH\nor die \"Cannot open $filename: $!\\n\" ;\n\n# Install DBM Filters\n$db->filterfetchkey  ( sub { s/\\0$//    } ) ;\n$db->filterstorekey  ( sub { $ .= \"\\0\" } ) ;\n$db->filterfetchvalue( sub { s/\\0$//    } ) ;\n$db->filterstorevalue( sub { $ .= \"\\0\" } ) ;\n\n$hash{\"abc\"} = \"def\" ;\nmy $a = $hash{\"ABC\"} ;\n# ...\nundef $db ;\nuntie %hash ;\n\nHopefully the contents of each of  the  filters  should  be  self-explanatory.  Both  \"fetch\"\nfilters remove the terminating NULL, and both \"store\" filters add a terminating NULL.\n"
                },
                {
                    "name": "Another Example -- Key is a C int.",
                    "content": "Here  is  another  real-life  example.  By default, whenever Perl writes to a DBM database it\nalways writes the key and value as strings. So when you use this:\n\n$hash{12345} = \"something\" ;\n\nthe key 12345 will get stored in the DBM database as  the  5  byte  string  \"12345\".  If  you\nactually  want  the  key  to  be  stored in the DBM database as a C int, you will have to use\n\"pack\" when writing, and \"unpack\" when reading.\n\nHere is a DBM Filter that does it:\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\nmy %hash ;\nmy $filename = \"filt\" ;\nunlink $filename ;\n\n\nmy $db = tie %hash, 'DBFile', $filename, OCREAT|ORDWR, 0666, $DBHASH\nor die \"Cannot open $filename: $!\\n\" ;\n\n$db->filterfetchkey  ( sub { $ = unpack(\"i\", $) } ) ;\n$db->filterstorekey  ( sub { $ = pack (\"i\", $) } ) ;\n$hash{123} = \"def\" ;\n# ...\nundef $db ;\nuntie %hash ;\n\nThis time only two filters have been used -- we only need to manipulate the contents  of  the\nkey, so it wasn't necessary to install any value filters.\n"
                }
            ]
        },
        "HINTS AND TIPS": {
            "content": "",
            "subsections": [
                {
                    "name": "Locking: The Trouble with fd",
                    "content": "Until  version  1.72  of this module, the recommended technique for locking DBFile databases\nwas to flock the filehandle returned from the \"fd\" function. Unfortunately this technique has\nbeen shown to be fundamentally flawed (Kudos to David Harris for tracking this down). Use  it\nat your own peril!\n\nThe locking technique went like this.\n\n$db = tie(%db, 'DBFile', 'foo.db', OCREAT|ORDWR, 0644)\n|| die \"dbcreat foo.db $!\";\n$fd = $db->fd;\nopen(DBFH, \"+<&=$fd\") || die \"dup $!\";\nflock (DBFH, LOCKEX) || die \"flock: $!\";\n...\n$db{\"Tom\"} = \"Jerry\" ;\n...\nflock(DBFH, LOCKUN);\nundef $db;\nuntie %db;\nclose(DBFH);\n\nIn simple terms, this is what happens:\n\n1.   Use \"tie\" to open the database.\n\n2.   Lock the database with fd & flock.\n\n3.   Read & Write to the database.\n\n4.   Unlock and close the database.\n\nHere  is  the crux of the problem. A side-effect of opening the DBFile database in step 2 is\nthat an initial block from the database will get read from disk and cached in memory.\n\nTo see why this is a problem, consider what can happen when two processes, say \"A\"  and  \"B\",\nboth  want to update the same DBFile database using the locking steps outlined above. Assume\nprocess \"A\" has already opened the database and has a write  lock,  but  it  hasn't  actually\nupdated  the  database  yet (it has finished step 2, but not started step 3 yet). Now process\n\"B\" tries to open the same database - step 1 will succeed, but it will block on step 2  until\nprocess  \"A\"  releases  the lock. The important thing to notice here is that at this point in\ntime both processes will have cached identical initial blocks from the database.\n\nNow process \"A\" updates the database and happens to change some  of  the  data  held  in  the\ninitial  buffer.  Process  \"A\" terminates, flushing all cached data to disk and releasing the\ndatabase lock. At this point the database on disk will correctly reflect the changes made  by\nprocess \"A\".\n\nWith  the  lock  released,  process  \"B\"  can  now continue. It also updates the database and\nunfortunately it too modifies the data that was in its initial buffer. Once  that  data  gets\nflushed to disk it will overwrite some/all of the changes process \"A\" made to the database.\n\nThe  result  of  this scenario is at best a database that doesn't contain what you expect. At\nworst the database will corrupt.\n\nThe above won't happen every time competing process update the same DBFile database, but  it\ndoes illustrate why the technique should not be used.\n"
                },
                {
                    "name": "Safe ways to lock a database",
                    "content": "Starting  with  version  2.x,  Berkeley  DB  has internal support for locking.  The companion\nmodule to this one, BerkeleyDB <https://metacpan.org/pod/BerkeleyDB>, provides  an  interface\nto  this  locking  functionality.  If  you are serious about locking Berkeley DB databases, I\nstrongly recommend using BerkeleyDB <https://metacpan.org/pod/BerkeleyDB>.\n\nIf using BerkeleyDB <https://metacpan.org/pod/BerkeleyDB> isn't an option, there are a number\nof modules available on CPAN that can be used  to  implement  locking.  Each  one  implements\nlocking  differently  and  has  different  goals  in  mind. It is therefore worth knowing the\ndifference, so that you can pick the right one for  your  application.  Here  are  the  three\nlocking wrappers:\n"
                },
                {
                    "name": "Tie::DB_Lock",
                    "content": "A DBFile wrapper which creates copies of the database file for read access, so that you\nhave  a  kind  of  a  multiversioning concurrent read system. However, updates are still\nserial. Use for databases where reads may be lengthy and consistency problems may occur.\n"
                },
                {
                    "name": "Tie::DB_LockFile",
                    "content": "A DBFile wrapper that has the ability to lock and unlock the database while it is being\nused. Avoids the tie-before-flock problem by simply re-tie-ing the database when you get\nor drop a lock.  Because of the flexibility in dropping and re-acquiring the lock in the\nmiddle of a session, this can be massaged into a system that will work with long updates\nand/or reads if the application follows the hints in the POD documentation.\n"
                },
                {
                    "name": "DB_File::Lock",
                    "content": "An extremely lightweight DBFile wrapper that simply flocks a  lockfile  before  tie-ing\nthe database and drops the lock after the untie. Allows one to use the same lockfile for\nmultiple  databases  to  avoid  deadlock  problems,  if desired. Use for databases where\nupdates are reads are quick and simple flock locking semantics are enough.\n"
                },
                {
                    "name": "Sharing Databases With C Applications",
                    "content": "There is no technical reason why a Berkeley DB database cannot be shared by both a Perl and a\nC application.\n\nThe vast majority of problems that are reported in this area boil down to  the  fact  that  C\nstrings are NULL terminated, whilst Perl strings are not. See \"DBM FILTERS\" for a generic way\nto work around this problem.\n\nHere is a real example. Netscape 2.0 keeps a record of the locations you visit along with the\ntime  you  last  visited  them  in  a  DBHASH  database.  This is usually stored in the file\n~/.netscape/history.db. The key field in the database is the location string  and  the  value\nfield is the time the location was last visited stored as a 4 byte binary value.\n\nIf  you  haven't already guessed, the location string is stored with a terminating NULL. This\nmeans you need to be careful when accessing the database.\n\nHere is a snippet of code that is loosely based on Tom Christiansen's ggh  script  (available\nfrom your nearest CPAN archive in authors/id/TOMC/scripts/nshist.gz).\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\nuse Fcntl ;\n\nmy ($dotdir, $HISTORY, %histdb, $href, $binarytime, $date) ;\n$dotdir = $ENV{HOME} || $ENV{LOGNAME};\n\n$HISTORY = \"$dotdir/.netscape/history.db\";\n\ntie %histdb, 'DBFile', $HISTORY\nor die \"Cannot open $HISTORY: $!\\n\" ;;\n\n# Dump the complete database\nwhile ( ($href, $binarytime) = each %histdb ) {\n\n# remove the terminating NULL\n$href =~ s/\\x00$// ;\n\n# convert the binary time into a user friendly string\n$date = localtime unpack(\"V\", $binarytime);\nprint \"$date $href\\n\" ;\n}\n\n# check for the existence of a specific key\n# remember to add the NULL\nif ( $binarytime = $histdb{\"http://mox.perl.com/\\x00\"} ) {\n$date = localtime unpack(\"V\", $binarytime) ;\nprint \"Last visited mox.perl.com on $date\\n\" ;\n}\nelse {\nprint \"Never visited mox.perl.com\\n\"\n}\n\nuntie %histdb ;\n"
                },
                {
                    "name": "The untie() Gotcha",
                    "content": "If  you  make  use of the Berkeley DB API, it is very strongly recommended that you read \"The\nuntie Gotcha\" in perltie.\n\nEven if you don't currently make use of the API interface, it is still worth reading it.\n\nHere is an example which illustrates the problem from a DBFile perspective:\n\nuse DBFile ;\nuse Fcntl ;\n\nmy %x ;\nmy $X ;\n\n$X = tie %x, 'DBFile', 'tst.fil' , ORDWR|OTRUNC\nor die \"Cannot tie first time: $!\" ;\n\n$x{123} = 456 ;\n\nuntie %x ;\n\ntie %x, 'DBFile', 'tst.fil' , ORDWR|OCREAT\nor die \"Cannot tie second time: $!\" ;\n\nuntie %x ;\n\nWhen run, the script will produce this error message:\n\nCannot tie second time: Invalid argument at bad.file line 14.\n\nAlthough the error message above refers to the second tie()  statement  in  the  script,  the\nsource of the problem is really with the untie() statement that precedes it.\n\nHaving  read  perltie  you will probably have already guessed that the error is caused by the\nextra copy of the tied object stored in $X.  If you haven't, then the problem boils  down  to\nthe fact that the DBFile destructor, DESTROY, will not be called until all references to the\ntied  object  are destroyed. Both the tied variable, %x, and $X above hold a reference to the\nobject. The call to untie() will destroy the first, but $X still holds a valid reference,  so\nthe  destructor  will not get called and the database file tst.fil will remain open. The fact\nthat Berkeley DB then reports the attempt to open a database that is  already  open  via  the\ncatch-all \"Invalid argument\" doesn't help.\n\nIf you run the script with the \"-w\" flag the error message becomes:\n\nuntie attempted while 1 inner references still exist at bad.file line 12.\nCannot tie second time: Invalid argument at bad.file line 14.\n\nwhich  pinpoints the real problem. Finally the script can now be modified to fix the original\nproblem by destroying the API object before the untie:\n\n...\n$x{123} = 456 ;\n\nundef $X ;\nuntie %x ;\n\n$X = tie %x, 'DBFile', 'tst.fil' , ORDWR|OCREAT\n...\n"
                }
            ]
        },
        "COMMON QUESTIONS": {
            "content": "",
            "subsections": [
                {
                    "name": "Why is there Perl source in my database?",
                    "content": "If you look at the contents of a database file created by DBFile,  there  can  sometimes  be\npart of a Perl script included in it.\n\nThis  happens  because  Berkeley  DB  uses  dynamic  memory  to  allocate  buffers which will\nsubsequently be written to the database file. Being dynamic, the memory could have been  used\nfor  anything before DB malloced it. As Berkeley DB doesn't clear the memory once it has been\nallocated, the unused portions will contain random junk. In the case where a Perl script gets\nwritten to the database, the random junk will correspond to an area of  dynamic  memory  that\nhappened to be used during the compilation of the script.\n\nUnless  you don't like the possibility of there being part of your Perl scripts embedded in a\ndatabase file, this is nothing to worry about.\n"
                },
                {
                    "name": "How do I store complex data structures with DB_File?",
                    "content": "Although DBFile cannot do this directly, there is a module  which  can  layer  transparently\nover DBFile to accomplish this feat.\n\nCheck out the MLDBM module, available on CPAN in the directory modules/by-module/MLDBM.\n"
                },
                {
                    "name": "What does \"wide character in subroutine entry\" mean?",
                    "content": "You  will  usually get this message if you are working with UTF-8 data and want to read/write\nit from/to a Berkeley DB database file.\n\nThe easist way to deal with this issue is to  use  the  pre-defined  \"utf8\"  DBMFilter  (see\nDBMFilter) that was designed to deal with this situation.\n\nThe example below shows what you need if both the key and value are expected to be in UTF-8.\n\nuse DBFile;\nuse DBMFilter;\n\nmy $db = tie %h, 'DBFile', '/tmp/try.db', OCREAT|ORDWR, 0666, $DBBTREE;\n$db->FilterKeyPush('utf8');\n$db->FilterValuePush('utf8');\n\nmy $key = \"\\N{LATIN SMALL LETTER A WITH ACUTE}\";\nmy $value = \"\\N{LATIN SMALL LETTER E WITH ACUTE}\";\n$h{ $key } = $value;\n"
                },
                {
                    "name": "What does \"Invalid Argument\" mean?",
                    "content": "You  will  get  this  error  message  when  one of the parameters in the \"tie\" call is wrong.\nUnfortunately there are quite a few parameters to get wrong, so it can be difficult to figure\nout which one it is.\n\nHere are a couple of possibilities:\n\n1.   Attempting to reopen a database without closing it.\n\n2.   Using the OWRONLY flag.\n"
                },
                {
                    "name": "What does \"Bareword 'DB_File' not allowed\" mean?",
                    "content": "You will encounter this particular error message when you have the \"strict 'subs'\" pragma (or\nthe full strict pragma) in your script.  Consider this script:\n\nuse warnings ;\nuse strict ;\nuse DBFile ;\nmy %x ;\ntie %x, DBFile, \"filename\" ;\n\nRunning it produces the error in question:\n\nBareword \"DBFile\" not allowed while \"strict subs\" in use\n\nTo get around the error, place the word \"DBFile\" in either single  or  double  quotes,  like\nthis:\n\ntie %x, \"DBFile\", \"filename\" ;\n\nAlthough  it  might  seem  like  a  real pain, it is really worth the effort of having a \"use\nstrict\" in all your scripts.\n"
                }
            ]
        },
        "REFERENCES": {
            "content": "Articles that are either about DBFile or make use of it.\n\n1.   Full-Text Searching in Perl, Tim Kientzle (tkientzle@ddj.com), Dr. Dobb's Journal, Issue\n295, January 1999, pp 34-41\n",
            "subsections": []
        },
        "HISTORY": {
            "content": "Moved to the Changes file.\n",
            "subsections": []
        },
        "BUGS": {
            "content": "Some older versions of Berkeley DB had problems with fixed length  records  using  the  RECNO\nfile format. This problem has been fixed since version 1.85 of Berkeley DB.\n\nI  am sure there are bugs in the code. If you do find any, or can suggest any enhancements, I\nwould welcome your comments.\n",
            "subsections": []
        },
        "SUPPORT": {
            "content": "General       feedback/questions/bug       reports       should       be       sent        to\n<https://github.com/pmqs/DBFile/issues>                    (preferred)                    or\n<https://rt.cpan.org/Public/Dist/Display.html?Name=DBFile>.\n",
            "subsections": []
        },
        "AVAILABILITY": {
            "content": "DBFile comes with the standard Perl source distribution. Look in the directory  ext/DBFile.\nGiven  the  amount of time between releases of Perl the version that ships with Perl is quite\nlikely to be out of date, so the most recent version can always be found on CPAN (see  \"CPAN\"\nin perlmodlib for details), in the directory modules/by-module/DBFile.\n\nDBFile  is  designed  to  work  with  any  version  of  Berkeley  DB,  but is limited to the\nfunctionality provided by version 1. If you want to make use of the new features available in\nBerkeley    DB    2.x,     or     greater,     use     the     Perl     module     BerkeleyDB\n<https://metacpan.org/pod/BerkeleyDB> instead.\n\nThe         official         web         site         for        Berkeley        DB        is\n<http://www.oracle.com/technology/products/berkeley-db/db/index.html>.    All   versions   of\nBerkeley DB are available there.\n\nAlternatively,  Berkeley  DB  version  1  is  available  at  your  nearest  CPAN  archive  in\nsrc/misc/db.1.85.tar.gz.\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright (c) 1995-2022 Paul Marquess. All rights reserved. This program  is  free  software;\nyou can redistribute it and/or modify it under the same terms as Perl itself.\n\nAlthough DBFile is covered by the Perl license, the library it makes use of, namely Berkeley\nDB,   is   not.   Berkeley  DB  has  its  own  copyright  and  its  own  license.   See  AGPL\n<https://www.oracle.com/downloads/licenses/berkeleydb-oslicense.html>   for   more   details.\nPlease  take  the  time to read the Berkeley DB license and decide how it impacts your use of\nthis Perl module.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "perl, dbopen(3), hash(3), recno(3), btree(3), perldbmfilter, DBMFilter\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "The DBFile interface was written by Paul Marquess <pmqs@cpan.org>.\n\nperl v5.38.2                                 2026-08-18                               DBFile(3perl)",
            "subsections": []
        }
    },
    "summary": "DBFile - Perl5 access to Berkeley DB version 1.x",
    "flags": [],
    "examples": [],
    "see_also": [
        {
            "name": "dbopen",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/dbopen/3/json"
        },
        {
            "name": "hash",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/hash/3/json"
        },
        {
            "name": "recno",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/recno/3/json"
        },
        {
            "name": "btree",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/btree/3/json"
        }
    ]
}