{
    "mode": "perldoc",
    "parameter": "DB_File",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/DB_File/json",
    "generated": "2026-06-09T18:29:29Z",
    "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 DB\nversion 2 or greater\"). It is assumed that you have a copy of the Berkeley DB manual pages at\nhand when reading this documentation. The interface defined here mirrors the Berkeley DB\ninterface 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 supported by\nBerkeley 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 your\nown 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 binary\ntree.\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 order.\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 key\nwill consist of a record (line) number.\n",
            "subsections": [
                {
                    "name": "Using DBFile 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 to\nwork like version 1. This feature allows DBFile scripts that were built with version 1 to be\nmigrated 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. If\nyou 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 DBFile\nto use Berkeley DB version 2 or greater, your databases can be recreated using \"dbload\". Refer\nto 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 (for\nthe DBRECNO file type).\n\nIn addition to the tie() interface, it is also possible to access most of the functions provided\nin 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 for"
                },
                {
                    "name": "dbopen",
                    "content": "DB*\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 chosen,\nthe final parameter, *openinfo* points to a data structure which allows tailoring of the\nspecific 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 has\nthree 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 most\napplications. If you do need to create extra instances of these objects, constructors are\navailable for each file type.\n\nHere are examples of the constructors and the valid options available for DBHASH, DBBTREE and\nDBRECNO 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 counterpart.\nLike their C counterparts, all are set to a default values - that means you don't have to set\n*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 \"hash\",\n\"compare\" and \"prefix\" store pointers to C functions. In DBFile these keys are used to store\nreferences 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 them\ntake 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\" in\nC) in place of the filename. DBFile uses \"undef\" instead of NULL to provide this functionality.\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\nA Simple Example\nThis 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",
            "subsections": []
        },
        "DBBTREE": {
            "content": "The DBBTREE format is useful when you want to store data in a given order. By default the keys\nwill be stored in lexical order, but as you will see from the example shown in the next section,\nit 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 to\nthe second one would overwrite the first. If duplicates are allowed for (with the RDUP\nflag discussed below), only a single copy of duplicate keys is stored in the database ---\nso (again with example above) assigning three values to the keys: 'KEY', 'Key', and 'key'\nwould leave just the first key: 'KEY' in the database with three values. For some\nsituations this results in information loss, so care should be taken to provide fully\nqualified comparison functions when necessary. For example, the above comparison routine\ncould be modified to additionally compare case-sensitively if two keys are equal in the\ncase 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. (note:\nin versions of the db library prior to about November 1996, such duplicate keys were\nretained so it was possible to recover the original keys in sets of keys that compared as\nequal).\n"
                },
                {
                    "name": "Handling Duplicate Keys",
                    "content": "The BTREE file type optionally allows a single key to be associated with an arbitrary number of\nvalues. This option is enabled by setting the flags element of $DBBTREE to RDUP when creating\nthe database.\n\nThere are some difficulties in using the tied hash interface if you want to manipulate a BTREE\ndatabase 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 the\nassociative array interface is used to fetch the value associated with a given key, it will only\never retrieve the first value.\n\nAlthough it may not be immediately obvious from the code above, the associative array interface\ncan be used to write values with duplicate keys, but it cannot be used to read them back from\nthe 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 both\nthe \"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 the\nkey \"Wall\".\n\nTo make life easier when dealing with duplicate keys, DBFile comes with a few utility methods.\n\nThe getdup() Method\nThe \"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 value\noccurred 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\nThe finddup() Method\n$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\nThe deldup() Method\n$status = $X->deldup($key, $value) ;\n\nThis method deletes a specific key/value pair. It returns 0 if they exist and have been deleted\nsuccessfully. 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 is\n*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 begins\nat 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 -1\nrefers to the last element of the array, -2 the second last, and so on. Attempting to access an\nelement 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 from\nthe 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 use\nof any of the options in the openinfo parameter. This documentation error will be fixed in the\nnext 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\nA Simple Example\nHere 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 array\nlength will not work with a tied array.\n\nTo make the interface more useful for older versions of Perl, a number of methods are supplied\nwith DBFile to simulate the missing array operations. All these methods are accessed via the\nobject returned from the tie call.\n\nHere are the methods:\n\n$X->push(list) ;\nPushes the elements of \"list\" to the end of the array.\n\n$value = $X->pop ;\nRemoves and returns the last element of the array.\n\n$X->shift\nRemoves and returns the first element of the array.\n\n$X->unshift(list) ;\nPushes the elements of \"list\" to the start of the array.\n\n$X->length\nReturns the number of elements in the array.\n\n$X->splice(offset, length, elements);\nReturns 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 also\nmakes 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 the\nrecord 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 direct\nuse 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 database\nfile will *not* be closed until both the tied variable is untied and all copies of the saved\nobject 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 details.\nThe 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 in\nthe 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 will\nprobably 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 below\nare also available. Refer to the Berkeley DB documentation for the precise meaning of the flags\nvalues.\n\nBelow is a list of the methods available.\n\n$status = $X->get($key, $value [, $flags]) ;\nGiven 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\n$status = $X->put($key, $value [, $flags]) ;\nStores the key/value pair in the database.\n\nIf you use either the RIAFTER or RIBEFORE flags, the $key parameter will have the record\nnumber of the inserted key/value pair set.\n\nValid flags are RCURSOR, RIAFTER, RIBEFORE, RNOOVERWRITE and RSETCURSOR.\n\n$status = $X->del($key [, $flags]) ;\nRemoves 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\n$status = $X->fd ;\nReturns 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\n$status = $X->seq($key, $value, $flags) ;\nThis interface allows sequential retrieval from the database. See dbopen for full details.\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\n$status = $X->sync([$flags]) ;\nFlushes any cached buffers to disk.\n\nRRECNOSYNC is the only valid flag at present.\n",
            "subsections": []
        },
        "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 reading\nfrom 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 and\ncomes with a number of \"canned\" filters that cover some of the common use-cases.\n\nUse of the DBMFilter module is recommended.\n\nDBM Filter Low-level API\nThere 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 reference\nto a sub. The only difference between them is the place that the filter is installed.\n\nTo summarise:\n\nfilterstorekey\nIf a filter has been installed with this method, it will be invoked every time you write a\nkey to a DBM database.\n\nfilterstorevalue\nIf a filter has been installed with this method, it will be invoked every time you write a\nvalue to a DBM database.\n\nfilterfetchkey\nIf a filter has been installed with this method, it will be invoked every time you read a\nkey from a DBM database.\n\nfilterfetchvalue\nIf a filter has been installed with this method, it will be invoked every time you read a\nvalue 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",
            "subsections": [
                {
                    "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 filter\nis 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\nthird-party C application. The C application assumes that *all* keys and values are NULL\nterminated. Unfortunately when Perl writes to DBM databases it doesn't use NULL termination, so\nyour Perl application will have to manage NULL termination itself. When you write to the\ndatabase you will 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 application\ncode and have a mechanism that automatically added the terminating NULL to all keys and values\nwhenever you write to the database and have them removed when you read from the database. As I'm\nsure you have already guessed, this is a problem that DBM Filters can fix 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\" filters\nremove 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 always\nwrites 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 actually\nwant the key to be stored in the DBM database as a C int, you will have to use \"pack\" when\nwriting, 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 key,\nso 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 was\nto flock the filehandle returned from the \"fd\" function. Unfortunately this technique has been\nshown to be fundamentally flawed (Kudos to David Harris for tracking this down). Use it at your\nown 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 that\nan 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\", both\nwant to update the same DBFile database using the locking steps outlined above. Assume process\n\"A\" has already opened the database and has a write lock, but it hasn't actually updated the\ndatabase yet (it has finished step 2, but not started step 3 yet). Now process \"B\" tries to open\nthe same database - step 1 will succeed, but it will block on step 2 until process \"A\" releases\nthe lock. The important thing to notice here is that at this point in time both processes will\nhave 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 initial\nbuffer. Process \"A\" terminates, flushing all cached data to disk and releasing the database\nlock. At this point the database on disk will correctly reflect the changes made by process \"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 worst\nthe 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 module to\nthis one, BerkeleyDB <https://metacpan.org/pod/BerkeleyDB>, provides an interface to this\nlocking functionality. If you are serious about locking Berkeley DB databases, I strongly\nrecommend using BerkeleyDB <https://metacpan.org/pod/BerkeleyDB>.\n\nIf using BerkeleyDB <https://metacpan.org/pod/BerkeleyDB> isn't an option, there are a number of\nmodules available on CPAN that can be used to implement locking. Each one implements locking\ndifferently and has different goals in mind. It is therefore worth knowing the difference, so\nthat you can pick the right one for your application. Here are the three locking wrappers:\n\nTie::DBLock\nA 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 serial.\nUse for databases where reads may be lengthy and consistency problems may occur.\n\nTie::DBLockFile\nA 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 or\ndrop a lock. Because of the flexibility in dropping and re-acquiring the lock in the middle\nof a session, this can be massaged into a system that will work with long updates and/or\nreads if the application follows the hints in the POD documentation.\n\nDBFile::Lock\nAn extremely lightweight DBFile wrapper that simply flocks a lockfile before tie-ing the\ndatabase 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 updates\nare 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 C\napplication.\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 to\nwork 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 field\nis 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\nThe untie() Gotcha\nIf 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 source\nof 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 extra\ncopy of the tied object stored in $X. If you haven't, then the problem boils down to the fact\nthat the DBFile destructor, DESTROY, will not be called until *all* references to the tied\nobject are destroyed. Both the tied variable, %x, and $X above hold a reference to the object.\nThe call to untie() will destroy the first, but $X still holds a valid reference, so the\ndestructor will not get called and the database file tst.fil will remain open. The fact that\nBerkeley DB then reports the attempt to open a database that is already open via the catch-all\n\"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": "Why is there Perl source in my database?\nIf you look at the contents of a database file created by DBFile, there can sometimes be part\nof a Perl script included in it.\n\nThis happens because Berkeley DB uses dynamic memory to allocate buffers which will subsequently\nbe written to the database file. Being dynamic, the memory could have been used for anything\nbefore DB malloced it. As Berkeley DB doesn't clear the memory once it has been allocated, the\nunused portions will contain random junk. In the case where a Perl script gets written to the\ndatabase, the random junk will correspond to an area of dynamic memory that happened to be used\nduring 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\nHow do I store complex data structures with DBFile?\nAlthough DBFile cannot do this directly, there is a module which can layer transparently over\nDBFile to accomplish this feat.\n\nCheck out the MLDBM module, available on CPAN in the directory modules/by-module/MLDBM.\n\nWhat does \"wide character in subroutine entry\" mean?\nYou will usually get this message if you are working with UTF-8 data and want to read/write it\nfrom/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\nWhat does \"Invalid Argument\" mean?\nYou 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\nWhat does \"Bareword 'DBFile' not allowed\" mean?\nYou 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 this:\n\ntie %x, \"DBFile\", \"filename\" ;\n\nAlthough it might seem like a real pain, it is really worth the effort of having a \"use strict\"\nin all your scripts.\n",
            "subsections": []
        },
        "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 file\nformat. 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\" in\nperlmodlib 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 functionality\nprovided by version 1. If you want to make use of the new features available in Berkeley DB 2.x,\nor greater, use the Perl module BerkeleyDB <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 Berkeley\nDB 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-2020 Paul Marquess. All rights reserved. This program is free software; you\ncan 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. Please take the time to read\nit.\n\nHere are a few words taken from the Berkeley DB FAQ (at\n<http://www.oracle.com/technology/products/berkeley-db/db/index.html>) regarding the license:\n\nDo I have to license DB to use it in Perl scripts?\n\nNo. The Berkeley DB license requires that software that uses\nBerkeley DB be freely redistributable. In the case of Perl, that\nsoftware is Perl, and not your scripts. Any Perl scripts that you\nwrite are your property, including scripts that make use of\nBerkeley DB. Neither the Perl license nor the Berkeley DB license\nplace any restriction on what you may do with them.\n\nIf you are in any doubt about the license situation, contact either the Berkeley DB authors or\nthe author of DBFile. See \"AUTHOR\" for details.\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",
            "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"
        }
    ]
}