This is Info file pm.info, produced by Makeinfo version 1.68 from the input file bigpm.texi.  File: pm.info, Node: Be/Query, Next: Befunge/Interpreter, Prev: Be/Attribute, Up: Module List do a Query for a given filesystem. ********************************** NAME ==== Be::Query - do a Query for a given filesystem. SYNOPSIS ======== use Be::Query; @files = Be::Query::Query($filesystem, $query); DESCRIPTION =========== do a Query for a given filesystem USAGE ===== @files = Be::Query::Query("/boot", "name=lib*.so"); $filesystem is a path anywhere in the target filesystem; $query is a query construction, of the form attribute op value [connector attribute op value] Such as (name = fido) || (size >= 500) See the below URLs for more information on constructing queries. AUTHOR ====== Tom Spindler, dogcow@globalcenter.net SEE ALSO ======== http://www.be.com/documentation/be_book/The%20Storage%20Kit/Query.html#14835:Zhead2:ZTheZPredicate,ZAttributes,ZandZIndices and http://www.be.com/documentation/be_book/The%20Storage%20Kit/Query.html29556:Zhead3:ZConstructingZaZPredicate give help on how to construct queries. (Sorry for the annoying URLs.)  File: pm.info, Node: Befunge/Interpreter, Next: Benchmark, Prev: Be/Query, Up: Module List Perl extension for interpreting befunge. **************************************** NAME ==== Befunge::Interpreter - Perl extension for interpreting befunge. SYNOPSIS ======== use Befunge::Interpreter; DESCRIPTION =========== Befunge::Interpreter is a fully Befunge-93 compliant Befunge interpreter written in Perl. The usage is easy. use Befunge::Interpreter; $interpreter = new Befunge::Interpreter; $interpreter->get_befunge("hello.bf"); $intrepreter->process_befunge(); That is all, so far. TO-DO ===== I have to add lots of stuff, update to Funge-98 spec... BUGS ==== I don't know of any CONTACT ======= Any problems contact xjharding@newbedford.k12.ma.us  File: pm.info, Node: Benchmark, Next: BerkDB, Prev: Befunge/Interpreter, Up: Module List benchmark running times of Perl code ************************************ NAME ==== Benchmark - benchmark running times of Perl code SYNOPSIS ======== timethis ($count, "code"); # Use Perl code in strings... timethese($count, { 'Name1' => '...code1...', 'Name2' => '...code2...', }); # ... or use subroutine references. timethese($count, { 'Name1' => sub { ...code1... }, 'Name2' => sub { ...code2... }, }); # cmpthese can be used both ways as well cmpthese($count, { 'Name1' => '...code1...', 'Name2' => '...code2...', }); cmpthese($count, { 'Name1' => sub { ...code1... }, 'Name2' => sub { ...code2... }, }); # ...or in two stages $results = timethese($count, { 'Name1' => sub { ...code1... }, 'Name2' => sub { ...code2... }, }, 'none' ); cmpthese( $results ) ; $t = timeit($count, '...other code...') print "$count loops of other code took:",timestr($t),"\n"; $t = countit($time, '...other code...') $count = $t->iters ; print "$count loops of other code took:",timestr($t),"\n"; DESCRIPTION =========== The Benchmark module encapsulates a number of routines to help you figure out how long it takes to execute some code. timethis - run a chunk of code several times timethese - run several chunks of code several times cmpthese - print results of timethese as a comparison chart timeit - run a chunk of code and see how long it goes countit - see how many times a chunk of code runs in a given time Methods ------- new Returns the current time. Example: use Benchmark; $t0 = new Benchmark; # ... your code here ... $t1 = new Benchmark; $td = timediff($t1, $t0); print "the code took:",timestr($td),"\n"; debug Enables or disable debugging by setting the `$Benchmark::Debug' flag: debug Benchmark 1; $t = timeit(10, ' 5 ** $Global '); debug Benchmark 0; iters Returns the number of iterations. Standard Exports ---------------- The following routines will be exported into your namespace if you use the Benchmark module: timeit(COUNT, CODE) Arguments: COUNT is the number of times to run the loop, and CODE is the code to run. CODE may be either a code reference or a string to be eval'd; either way it will be run in the caller's package. Returns: a Benchmark object. timethis ( COUNT, CODE, [ TITLE, [ STYLE ]] ) Time COUNT iterations of CODE. CODE may be a string to eval or a code reference; either way the CODE will run in the caller's package. Results will be printed to STDOUT as TITLE followed by the times. TITLE defaults to "timethis COUNT" if none is provided. STYLE determines the format of the output, as described for timestr() below. The COUNT can be zero or negative: this means the *minimum number of CPU seconds* to run. A zero signifies the default of 3 seconds. For example to run at least for 10 seconds: timethis(-10, $code) or to run two pieces of code tests for at least 3 seconds: timethese(0, { test1 => '...', test2 => '...'}) CPU seconds is, in UNIX terms, the user time plus the system time of the process itself, as opposed to the real (wallclock) time and the time spent by the child processes. Less than 0.1 seconds is not accepted (-0.01 as the count, for example, will cause a fatal runtime exception). Note that the CPU seconds is the minimum time: CPU scheduling and other operating system factors may complicate the attempt so that a little bit more time is spent. The benchmark output will, however, also tell the number of $code runs/second, which should be a more interesting number than the actually spent seconds. Returns a Benchmark object. timethese ( COUNT, CODEHASHREF, [ STYLE ] ) The CODEHASHREF is a reference to a hash containing names as keys and either a string to eval or a code reference for each value. For each (KEY, VALUE) pair in the CODEHASHREF, this routine will call timethis(COUNT, VALUE, KEY, STYLE) The routines are called in string comparison order of KEY. The COUNT can be zero or negative, see timethis(). Returns a hash of Benchmark objects, keyed by name. timediff ( T1, T2 ) Returns the difference between two Benchmark times as a Benchmark object suitable for passing to timestr(). timestr ( TIMEDIFF, [ STYLE, [ FORMAT ] ] ) Returns a string that formats the times in the TIMEDIFF object in the requested STYLE. TIMEDIFF is expected to be a Benchmark object similar to that returned by timediff(). STYLE can be any of 'all', 'none', 'noc', 'nop' or 'auto'. 'all' shows each of the 5 times available ('wallclock' time, user time, system time, user time of children, and system time of children). 'noc' shows all except the two children times. 'nop' shows only wallclock and the two children times. 'auto' (the default) will act as 'all' unless the children times are both zero, in which case it acts as 'noc'. 'none' prevents output. FORMAT is the `printf(3)' in this node-style format specifier (without the leading '%') to use to print the times. It defaults to '5.2f'. Optional Exports ---------------- The following routines will be exported into your namespace if you specifically ask that they be imported: clearcache ( COUNT ) Clear the cached time for COUNT rounds of the null loop. clearallcache ( ) Clear all cached times. cmpthese ( COUT, CODEHASHREF, [ STYLE ] ) cmpthese ( RESULTSHASHREF ) Optionally calls timethese(), then outputs comparison chart. This chart is sorted from slowest to fastest, and shows the percent speed difference between each pair of tests. Can also be passed the data structure that timethese() returns: $results = timethese( .... ); cmpthese( $results ); Returns the data structure returned by timethese() (or passed in). countit(TIME, CODE) Arguments: TIME is the minimum length of time to run CODE for, and CODE is the code to run. CODE may be either a code reference or a string to be eval'd; either way it will be run in the caller's package. TIME is not negative. countit() will run the loop many times to calculate the speed of CODE before running it for TIME. The actual time run for will usually be greater than TIME due to system clock resolution, so it's best to look at the number of iterations divided by the times that you are concerned with, not just the iterations. Returns: a Benchmark object. disablecache ( ) Disable caching of timings for the null loop. This will force Benchmark to recalculate these timings for each new piece of code timed. enablecache ( ) Enable caching of timings for the null loop. The time taken for COUNT rounds of the null loop will be calculated only once for each different COUNT used. timesum ( T1, T2 ) Returns the sum of two Benchmark times as a Benchmark object suitable for passing to timestr(). NOTES ===== The data is stored as a list of values from the time and times functions: ($real, $user, $system, $children_user, $children_system, $iters) in seconds for the whole loop (not divided by the number of rounds). The timing is done using time(3) and times(3). Code is executed in the caller's package. The time of the null loop (a loop with the same number of rounds but empty loop body) is subtracted from the time of the real loop. The null loop times can be cached, the key being the number of rounds. The caching can be controlled using calls like these: clearcache($key); clearallcache(); disablecache(); enablecache(); Caching is off by default, as it can (usually slightly) decrease accuracy and does not usually noticably affect runtimes. EXAMPLES ======== For example, use Benchmark;$x=3;cmpthese(-5,{a=>sub{$x*$x},b=>sub{$x**2}}) outputs something like this: Benchmark: running a, b, each for at least 5 CPU seconds... a: 10 wallclock secs ( 5.14 usr + 0.13 sys = 5.27 CPU) @ 3835055.60/s (n=20210743) b: 5 wallclock secs ( 5.41 usr + 0.00 sys = 5.41 CPU) @ 1574944.92/s (n=8520452) Rate b a b 1574945/s -- -59% a 3835056/s 144% -- while use Benchmark; $x=3; $r=timethese(-5,{a=>sub{$x*$x},b=>sub{$x**2}},'none'); cmpthese($r); outputs something like this: Rate b a b 1559428/s -- -62% a 4152037/s 166% -- INHERITANCE =========== Benchmark inherits from no other class, except of course for Exporter. CAVEATS ======= Comparing eval'd strings with code references will give you inaccurate results: a code reference will show a slightly slower execution time than the equivalent eval'd string. The real time timing is done using time(2) and the granularity is therefore only one second. Short tests may produce negative figures because perl can appear to take longer to execute the empty loop than a short test; try: timethis(100,'1'); The system time of the null loop might be slightly more than the system time of the loop with the actual code and therefore the difference might end up being < 0. SEE ALSO ======== *Note Devel/DProf: Devel/DProf, - a Perl code profiler AUTHORS ======= Jarkko Hietaniemi <`jhi@iki.fi'>, Tim Bunce <`Tim.Bunce@ig.co.uk'> MODIFICATION HISTORY ==================== September 8th, 1994; by Tim Bunce. March 28th, 1997; by Hugo van der Sanden: added support for code references and the already documented 'debug' method; revamped documentation. April 04-07th, 1997: by Jarkko Hietaniemi, added the run-for-some-time functionality. September, 1999; by Barrie Slaymaker: math fixes and accuracy and efficiency tweaks. Added cmpthese(). A result is now returned from timethese(). Exposed countit() (was runfor()).  File: pm.info, Node: BerkDB, Next: BerkeleyDB, Prev: Benchmark, Up: Module List Perl extension for Berkeley DB version 2 **************************************** NAME ==== BerkDB - Perl extension for Berkeley DB version 2 SYNOPSIS ======== use BerkDB; $env = new BerkDB::Env [OPTIONS] ; $db = tie %hash, 'BerkDB::Hash', [OPTIONS] ; $db = new BerkDB::Hash [OPTIONS] ; $db = tie %hash, 'BerkDB::Btree', [OPTIONS] ; $db = new BerkDB::Btree [OPTIONS] ; $hash{$key} = $value ; $value = $hash{$key} ; each %hash ; keys %hash ; values %hash ; $status = $db->db_get() $status = $db->db_put() ; $status = $db->db_del() ; $status = $db->db_sync() ; $hash_ref = $db->db_stat() ; ($flag, $old_offset, $old_length) = $db->partial_set($offset, $length) ; ($flag, $old_offset, $old_length) = $db->partial_clear() ; $cursor = $db->db_cursor() ; $status = $cursor->c_get() ; $status = $cursor->c_put() ; $status = $cursor->c_del() ; $txn = $env->txn_begin() ; $status = $txn->txn_prepare() $status = $txn->txn_commit() $status = $txn->txn_abort() $status = $txn->txn_checkpoint() $status = $txn->txn_id() $status = $txn->txn_stat() $BerkDB::Error $BerkDB::db_version DESCRIPTION =========== *NOTE: This document is still under construction, so it is likely to be incomplete.* This Perl module provides an interface to most of the functionality available in Berkeley DB version 2. The reader is expected to be familiar with the Berkeley DB documentation. The db_appinit, db_cursor, db_open and db_txn man pages are particularly relevant. ENVIRONMENT CLASS ================= The equivalent of the Berkeley DB function `db_appinit'. It is only needed when you want to make use of locking, logging or transactions. Synopsis -------- $env = new BerkDB::Env [OPTIONS] [ -Home => $path, ] [ -Config => { name => value, name => value }, ] [ -ErrFile => filename or filehandle, ] [ -ErrPrefix => "string", ] [ -Flags => number, ] [ -Verbose => boolean, ] [ -LockMax => number, ] [ -LogMax => number, ] [ -TxnMax => number, ] Where the OPTIONS consist of any of the following: -Home -Config -ErrFile -ErrPrefix -Flags The Flags option can consist of one of more of the following or'ed together. DB_CREATE DB_INIT_LOCK DB_INIT_LOG DB_INIT_MPOOL DB_INIT_TXN DB_MPOOL_PRIVATE DB_NOMMAP DB_RECOVER DB_RECOVER_FATAL DB_THREAD DB_TXN_NOSYNC DB_USE_ENVIRON DB_USE_ENVIRON_ROOT -Verbose -LockMax -LogMax -TxnMax Methods ------- The environment class has the following methods: txn_begin $txn = $env->txn_begin() ; errPrefix $db->errPrefix("string") ; THE HASH CLASS ============== The equivalent of db_open with type DB_HASH. Two forms $db = new BerkDB::Hash [ -Filename => "filename" ] [ -Flags => ] [ -Property => ] [ -Mode => ] [ -Cachesize => ] [ -Lorder => ] [ -Pagesize => ] [ -Env => ] [ -Txn => ] [ -Ffactor => ] [ -Nelem => ] [ -Hash => ] and this $db = tie %hash, 'BerkDB::Hash', OPTIONS where OPTIONS are the same as for the new constructor. In addition to the standard set of options (see `COMMON OPTIONS' in this node) BerkDB::Hash supports these: -Property Used to specify additional flags. DB_DUP -Ffactor -Nelem -Hash Methods ------- See `COMMON DATABASE METHODS' in this node. A Simple Hash Example --------------------- use strict ; use BerkDB ; my %hash ; my $filename = "database" ; tie %hash, 'BerkDB::Hash', -Filename => $filename, -Flags => DB_CREATE, or die "Cannot open file $filename: $! $BerkDB::Error\n" ; $hash{"fred"} = "barney" ; $hash{"joe"} = "harry" ; untie %hash ; THE BTREE CLASS =============== Methods ------- See `COMMON DATABASE METHODS' in this node. Btree supports one extra method $ref = $db->db_stat() ; THE RECNO CLASS =============== Not implemented yet. COMMON OPTIONS ============== All database access class constructors support the common set of parameters defined below. -Filename The database filename. If no filename is specified, the database will be created in-memory, and removed once the program terminates. -Flags Specify how the database will be opened/created. The valid flags are: DB_CREATE DB_NOMMAP DB_RDONLY DB_THREAD DB_TRUNCATE The default is none. -Mode Determines the file protection when the database is created. Defaults to 0666. -Cachesize -Lorder -Pagesize -Env When working under a Berkeley DB environment, this parameter Defaults to no environment. -Txn COMMON DATABASE METHODS ======================= All the database interfaces support a common set of methods. $status = $db->db_get($key, $value [, $flags]) ---------------------------------------------- $status = $db->db_put($key, $value [, $flags]) ---------------------------------------------- $status = $db->db_del($key [, $flags]) -------------------------------------- $status = $db->db_sync() ------------------------ $cursor = $db->db_cursor() -------------------------- Creates a cursor object. See `CURSORS' in this node for details of the methods available when working with cursore. $fd = $db->db_fd() ------------------ ($flag, $old_offset, $old_length) = $db->partial_set($offset, $length) ; ------------------------------------------------------------------------ ($flag, $old_offset, $old_length) = $db->partial_clear() ; ---------------------------------------------------------- When the "tie" interface is used, reading from and writing to the database is achieved via the tied hash. CURSORS ======= A cursor is created with the `db_cursor' $status = $cursor->c_get($key, $value [,$flags]) ------------------------------------------------ $status = $cursor->c_put($key, $value [,$flags]) ------------------------------------------------ $status = $cursor->c_del($key, [,$flags]) ----------------------------------------- TRANSACTIONS ============ EXAMPLES ======== todo. HISTORY See the Changes file. =============================== AVAILABILITY The most recent version of *BerkDB* can always be found on CPAN (see `CPAN', *Note Perlmod: (perl.info)perlmod, for details), in the directory `modules/by-module/BerkDB'. ========================================================================================================================================================================================= The official web site for Berkeley DB is `http://www.sleepycat.com/db'. The ftp equivalent is `ftp.sleepycat.com:/pub'. COPYRIGHT ========= Copyright (c) 1997 Paul Marquess. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Although *BerkDB* is covered by the Perl license, the library it makes use of, namely Berkeley DB version 2, is not. Berkeley DB has its own copyright and its own license. Please take the time to read it. The license for Berkeley DB version 2, and how it relates to BerkDB does need some extra clarification. Here are are few words taken from the Berkeley DB FAQ regarding the version 2 license: The major difference is that the license for DB 2.0, when downloaded from the net, requires that the software that uses DB 2.0 be freely redistributable. That means that if you want to use BerkDB, and you have changed either the source for Berkeley DB or Perl, then the changes must be freely available. In the case of Perl, the term source refers to the complete source code for Perl (e.g. sv.c, toke.c, perl.h) and any external modules that you are using (e.g. BerkDB, Tk). Note that any Perl scripts that you write are your property - this includes scripts that make use of BerkDB. Neither the Perl license or the Berkeley DB license place any restriction on what you have to do with them. If you are in any doubt about the license situation, contact either the Berkeley DB authors or the author of BerkDB. See `"AUTHOR"' in this node for details. AUTHOR ====== Paul Marquess . Questions about Berkeley DB may be addressed to . SEE ALSO ======== perl(1), DB_File, Berkeley DB.  File: pm.info, Node: BerkeleyDB, Next: BikePower, Prev: BerkDB, Up: Module List Perl extension for Berkeley DB version 2 or 3 ********************************************* NAME ==== BerkeleyDB - Perl extension for Berkeley DB version 2 or 3 SYNOPSIS ======== use BerkeleyDB; $env = new BerkeleyDB::Env [OPTIONS] ; $db = tie %hash, 'BerkeleyDB::Hash', [OPTIONS] ; $db = new BerkeleyDB::Hash [OPTIONS] ; $db = tie %hash, 'BerkeleyDB::Btree', [OPTIONS] ; $db = new BerkeleyDB::Btree [OPTIONS] ; $db = tie %hash, 'BerkeleyDB::Recno', [OPTIONS] ; $db = new BerkeleyDB::Recno [OPTIONS] ; $db = tie %hash, 'BerkeleyDB::Queue', [OPTIONS] ; $db = new BerkeleyDB::Queue [OPTIONS] ; $db = new BerkeleyDB::Unknown [OPTIONS] ; $status = BerkeleyDB::db_remove [OPTIONS] $hash{$key} = $value ; $value = $hash{$key} ; each %hash ; keys %hash ; values %hash ; $status = $db->db_get() $status = $db->db_put() ; $status = $db->db_del() ; $status = $db->db_sync() ; $status = $db->db_close() ; $hash_ref = $db->db_stat() ; $status = $db->db_key_range(); $type = $db->type() ; $status = $db->status() ; $boolean = $db->byteswapped() ; ($flag, $old_offset, $old_length) = $db->partial_set($offset, $length) ; ($flag, $old_offset, $old_length) = $db->partial_clear() ; $cursor = $db->db_cursor([$flags]) ; $newcursor = $cursor->c_dup([$flags]); $status = $cursor->c_get() ; $status = $cursor->c_put() ; $status = $cursor->c_del() ; $status = $cursor->c_count() ; $status = $cursor->status() ; $status = $cursor->c_close() ; $cursor = $db->db_join() ; $status = $cursor->c_get() ; $status = $cursor->c_close() ; $status = $env->txn_checkpoint() $hash_ref = $env->txn_stat() $status = $env->setmutexlocks() $txn = $env->txn_begin() ; $status = $txn->txn_prepare() $status = $txn->txn_commit() $status = $txn->txn_abort() $status = $txn->txn_id() $BerkeleyDB::Error $BerkeleyDB::db_version # DBM Filters $old_filter = $db->filter_store_key ( sub { ... } ) ; $old_filter = $db->filter_store_value( sub { ... } ) ; $old_filter = $db->filter_fetch_key ( sub { ... } ) ; $old_filter = $db->filter_fetch_value( sub { ... } ) ; # deprecated, but supported $txn_mgr = $env->TxnMgr(); $status = $txn_mgr->txn_checkpoint() $hash_ref = $txn_mgr->txn_stat() $txn = $txn_mgr->txn_begin() ; DESCRIPTION =========== *NOTE: This document is still under construction. Expect it to be incomplete in places.* This Perl module provides an interface to most of the functionality available in Berkeley DB versions 2 and 3. In general it is safe to assume that the interface provided here to be identical to the Berkeley DB interface. The main changes have been to make the Berkeley DB API work in a Perl way. Note that if you are using Berkeley DB 2.x, the new features available in Berkeley DB 3.x are not available via this module. The reader is expected to be familiar with the Berkeley DB documentation. Where the interface provided here is identical to the Berkeley DB library and the... TODO The *db_appinit*, *db_cursor*, *db_open* and *db_txn* man pages are particularly relevant. The interface to Berkeley DB is implemented with a number of Perl classes. ENV CLASS ========= The *BerkeleyDB::Env* class provides an interface to the Berkeley DB function *db_appinit* in Berkeley DB 2.x or *db_env_create* and *DBENV->open* in Berkeley DB 3.x. Its purpose is to initialise a number of sub-systems that can then be used in a consistent way in all the databases you make use of the environment. If you don't intend using transactions, locking or logging, then you shouldn't need to make use of *BerkeleyDB::Env*. Synopsis -------- $env = new BerkeleyDB::Env [ -Home => $path, ] [ -Server => $name, ] [ -CacheSize => $number, ] [ -Config => { name => value, name => value }, ] [ -ErrFile => filename or filehandle, ] [ -ErrPrefix => "string", ] [ -Flags => number, ] [ -LockDetect => number, ] [ -Verbose => boolean, ] All the parameters to the BerkeleyDB::Env constructor are optional. -Home If present, this parameter should point to an existing directory. Any files that *aren't* specified with an absolute path in the sub-systems that are initialised by the BerkeleyDB::Env class will be assumed to live in the *Home* directory. For example, in the code fragment below the database "fred.db" will be opened in the directory "/home/databases" because it was specified as a relative path, but "joe.db" will be opened in "/other" because it was part of an absolute path. $env = new BerkeleyDB::Env -Home => "/home/databases" ... $db1 = new BerkeleyDB::Hash -Filename = "fred.db", -Env => $env ... $db2 = new BerkeleyDB::Hash -Filename = "/other/joe.db", -Env => $env ... -Server If present, this parameter should be the hostname of a server that is running the Berkeley DB RPC server. All databases will be accessed via the RPC server. -Cachesize If present, this parameter sets the size of the environments shared memory buffer pool. -Config This is a variation on the `-Home' parameter, but it allows finer control of where specific types of files will be stored. The parameter expects a reference to a hash. Valid keys are: *DB_DATA_DIR*, *DB_LOG_DIR* and *DB_TMP_DIR* The code below shows an example of how it can be used. $env = new BerkeleyDB::Env -Config => { DB_DATA_DIR => "/home/databases", DB_LOG_DIR => "/home/logs", DB_TMP_DIR => "/home/tmp" } ... -ErrFile Expects either the name of a file or a reference to a filehandle. Any errors generated internally by Berkeley DB will be logged to this file. -ErrPrefix Allows a prefix to be added to the error messages before they are sent to *-ErrFile*. -Flags The Flags parameter specifies both which sub-systems to initialise, as well as a number of environment-wide options. See the Berkeley DB documentation for more details of these options. Any of the following can be specified by OR'ing them: *DB_CREATE* If any of the files specified do not already exist, create them. *DB_INIT_CDB* Initialise the Concurrent Access Methods *DB_INIT_LOCK* Initialise the Locking sub-system. *DB_INIT_LOG* Initialise the Logging sub-system. *DB_INIT_MPOOL* Initialise the ... *DB_INIT_TXN* Initialise the ... *DB_MPOOL_PRIVATE* Initialise the ... *DB_INIT_MPOOL* is also specified. Initialise the ... *DB_NOMMAP* Initialise the ... *DB_RECOVER* *DB_RECOVER_FATAL* *DB_THREAD* *DB_TXN_NOSYNC* *DB_USE_ENVIRON* *DB_USE_ENVIRON_ROOT* -LockDetect Specifies what to do when a lock conflict occurs. The value should be one of *DB_LOCK_DEFAULT* *DB_LOCK_OLDEST* *DB_LOCK_RANDOM* *DB_LOCK_YOUNGEST* -Verbose Add extra debugging information to the messages sent to *-ErrFile*. Methods ------- The environment class has the following methods: $env->errPrefix("string") ; This method is identical to the *-ErrPrefix* flag. It allows the error prefix string to be changed dynamically. $txn = $env->TxnMgr() Constructor for creating a *TxnMgr* object. See `"TRANSACTIONS"' in this node for more details of using transactions. This method is deprecated. Access the transaction methods using the *txn_* methods below from the environment object directly. $env->txn_begin() TODO $env->txn_stat() TODO $env->txn_checkpoint() TODO $env->status() Returns the status of the last BerkeleyDB::Env method. $env->setmutexlocks() Only available in Berkeley Db 3.0 or greater. Calls *db_env_set_mutexlocks* when used with Berkeley DB 3.1.x. When used with Berkeley DB 3.0 or 3.2 and better it calls *DBENV->set_mutexlocks*. Examples -------- TODO. THE DATABASE CLASSES ==================== *BerkeleyDB* supports the following database formats: BerkeleyDB::Hash This database type allows arbitrary key/value pairs to be stored in data files. This is equivalent to the functionality provided by other hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though, the files created using BerkeleyDB::Hash are not compatible with any of the other packages mentioned. A default hashing algorithm, which will be adequate for most applications, is built into BerkeleyDB. If you do need to use your own hashing algorithm it is possible to write your own in Perl and have *BerkeleyDB* use it instead. BerkeleyDB::Btree The Btree format allows arbitrary key/value pairs to be stored in a B+tree. As with the BerkeleyDB::Hash format, it is possible to provide a user defined Perl routine to perform the comparison of keys. By default, though, the keys are stored in lexical order. BerkeleyDB::Recno TODO. BerkeleyDB::Queue TODO. BerkeleyDB::Unknown This isn't a database format at all. It is used when you want to open an existing Berkeley DB database without having to know what type is it. Each of the database formats described above is accessed via a corresponding *BerkeleyDB* class. These will be described in turn in the next sections. BerkeleyDB::Hash ================ Equivalent to calling *db_open* with type DB_HASH in Berkeley DB 2.x and calling *db_create* followed by *DB->open* with type DB_HASH in Berkeley DB 3.x. Two forms of constructor are supported: $db = new BerkeleyDB::Hash [ -Filename => "filename", ] [ -Subname => "sub-database name", ] [ -Flags => flags,] [ -Property => flags,] [ -Mode => number,] [ -Cachesize => number,] [ -Lorder => number,] [ -Pagesize => number,] [ -Env => $env,] [ -Txn => $txn,] # BerkeleyDB::Hash specific [ -Ffactor => number,] [ -Nelem => number,] [ -Hash => code reference,] [ -DupCompare => code reference,] and this [$db =] tie %hash, 'BerkeleyDB::Hash', [ -Filename => "filename", ] [ -Subname => "sub-database name", ] [ -Flags => flags,] [ -Property => flags,] [ -Mode => number,] [ -Cachesize => number,] [ -Lorder => number,] [ -Pagesize => number,] [ -Env => $env,] [ -Txn => $txn,] # BerkeleyDB::Hash specific [ -Ffactor => number,] [ -Nelem => number,] [ -Hash => code reference,] [ -DupCompare => code reference,] When the "tie" interface is used, reading from and writing to the database is achieved via the tied hash. In this case the database operates like a Perl associative array that happens to be stored on disk. In addition to the high-level tied hash interface, it is possible to make use of the underlying methods provided by Berkeley DB Options ------- In addition to the standard set of options (see `COMMON OPTIONS' in this node) BerkeleyDB::Hash supports these options: -Property Used to specify extra flags when opening a database. The following flags may be specified by logically OR'ing together one or more of the following values: *DB_DUP* When creating a new database, this flag enables the storing of duplicate keys in the database. If *DB_DUPSORT* is not specified as well, the duplicates are stored in the order they are created in the database. *DB_DUPSORT* Enables the sorting of duplicate keys in the database. Ignored if *DB_DUP* isn't also specified. -Ffactor -Nelem See the Berkeley DB documentation for details of these options. -Hash Allows you to provide a user defined hash function. If not specified, a default hash function is used. Here is a template for a user-defined hash function sub hash { my ($data) = shift ; ... # return the hash value for $data return $hash ; } tie %h, "BerkeleyDB::Hash", -Filename => $filename, -Hash => \&hash, ... See `""' in this node for an example. -DupCompare Used in conjunction with the *DB_DUPOSRT* flag. sub compare { my ($key, $key2) = @_ ; ... # return 0 if $key1 eq $key2 # -1 if $key1 lt $key2 # 1 if $key1 gt $key2 return (-1 , 0 or 1) ; } tie %h, "BerkeleyDB::Hash", -Filename => $filename, -Property => DB_DUP|DB_DUPSORT, -DupCompare => \&compare, ... Methods ------- BerkeleyDB::Hash only supports the standard database methods. See `COMMON DATABASE METHODS' in this node. A Simple Tied Hash Example -------------------------- use strict ; use BerkeleyDB ; use vars qw( %h $k $v ) ; my $filename = "fruit" ; unlink $filename ; tie %h, "BerkeleyDB::Hash", -Filename => $filename, -Flags => DB_CREATE or die "Cannot open file $filename: $! $BerkeleyDB::Error\n" ; # Add a few key/value pairs to the file $h{"apple"} = "red" ; $h{"orange"} = "orange" ; $h{"banana"} = "yellow" ; $h{"tomato"} = "red" ; # Check for existence of a key print "Banana Exists\n\n" if $h{"banana"} ; # Delete a key/value pair. delete $h{"apple"} ; # print the contents of the file while (($k, $v) = each %h) { print "$k -> $v\n" } untie %h ; here is the output: Banana Exists orange -> orange tomato -> red banana -> yellow Note that the like ordinary associative arrays, the order of the keys retrieved from a Hash database are in an apparently random order. Another Simple Hash Example --------------------------- Do the same as the previous example but not using tie. use strict ; use BerkeleyDB ; my $filename = "fruit" ; unlink $filename ; my $db = new BerkeleyDB::Hash -Filename => $filename, -Flags => DB_CREATE or die "Cannot open file $filename: $! $BerkeleyDB::Error\n" ; # Add a few key/value pairs to the file $db->db_put("apple", "red") ; $db->db_put("orange", "orange") ; $db->db_put("banana", "yellow") ; $db->db_put("tomato", "red") ; # Check for existence of a key print "Banana Exists\n\n" if $db->db_get("banana", $v) == 0; # Delete a key/value pair. $db->db_del("apple") ; # print the contents of the file my ($k, $v) = ("", "") ; my $cursor = $db->db_cursor() ; while ($cursor->c_get($k, $v, DB_NEXT) == 0) { print "$k -> $v\n" } undef $cursor ; undef $db ; Duplicate keys -------------- The code below is a variation on the examples above. This time the hash has been inverted. The key this time is colour and the value is the fruit name. The *DB_DUP* flag has been specified to allow duplicates. use strict ; use BerkeleyDB ; my $filename = "fruit" ; unlink $filename ; my $db = new BerkeleyDB::Hash -Filename => $filename, -Flags => DB_CREATE, -Property => DB_DUP or die "Cannot open file $filename: $! $BerkeleyDB::Error\n" ; # Add a few key/value pairs to the file $db->db_put("red", "apple") ; $db->db_put("orange", "orange") ; $db->db_put("green", "banana") ; $db->db_put("yellow", "banana") ; $db->db_put("red", "tomato") ; $db->db_put("green", "apple") ; # print the contents of the file my ($k, $v) = ("", "") ; my $cursor = $db->db_cursor() ; while ($cursor->c_get($k, $v, DB_NEXT) == 0) { print "$k -> $v\n" } undef $cursor ; undef $db ; here is the output: orange -> orange yellow -> banana red -> apple red -> tomato green -> banana green -> apple Sorting Duplicate Keys ---------------------- In the previous example, when there were duplicate keys, the values are sorted in the order they are stored in. The code below is identical to the previous example except the *DB_DUPSORT* flag is specified. use strict ; use BerkeleyDB ; my $filename = "fruit" ; unlink $filename ; my $db = new BerkeleyDB::Hash -Filename => $filename, -Flags => DB_CREATE, -Property => DB_DUP | DB_DUPSORT or die "Cannot open file $filename: $! $BerkeleyDB::Error\n" ; # Add a few key/value pairs to the file $db->db_put("red", "apple") ; $db->db_put("orange", "orange") ; $db->db_put("green", "banana") ; $db->db_put("yellow", "banana") ; $db->db_put("red", "tomato") ; $db->db_put("green", "apple") ; # print the contents of the file my ($k, $v) = ("", "") ; my $cursor = $db->db_cursor() ; while ($cursor->c_get($k, $v, DB_NEXT) == 0) { print "$k -> $v\n" } undef $cursor ; undef $db ; Notice that in the output below the duplicate values are sorted. orange -> orange yellow -> banana red -> apple red -> tomato green -> apple green -> banana Custom Sorting Duplicate Keys ----------------------------- Another variation TODO Changing the hash ----------------- TODO Using db_stat ------------- TODO BerkeleyDB::Btree ================= Equivalent to calling *db_open* with type DB_BTREE in Berkeley DB 2.x and calling *db_create* followed by *DB->open* with type DB_BTREE in Berkeley DB 3.x. Two forms of constructor are supported: $db = new BerkeleyDB::Btree [ -Filename => "filename", ] [ -Subname => "sub-database name", ] [ -Flags => flags,] [ -Property => flags,] [ -Mode => number,] [ -Cachesize => number,] [ -Lorder => number,] [ -Pagesize => number,] [ -Env => $env,] [ -Txn => $txn,] # BerkeleyDB::Btree specific [ -Minkey => number,] [ -Compare => code reference,] [ -DupCompare => code reference,] [ -Prefix => code reference,] and this [$db =] tie %hash, 'BerkeleyDB::Btree', [ -Filename => "filename", ] [ -Subname => "sub-database name", ] [ -Flags => flags,] [ -Property => flags,] [ -Mode => number,] [ -Cachesize => number,] [ -Lorder => number,] [ -Pagesize => number,] [ -Env => $env,] [ -Txn => $txn,] # BerkeleyDB::Btree specific [ -Minkey => number,] [ -Compare => code reference,] [ -DupCompare => code reference,] [ -Prefix => code reference,] Options ------- In addition to the standard set of options (see `COMMON OPTIONS' in this node) BerkeleyDB::Btree supports these options: -Property Used to specify extra flags when opening a database. The following flags may be specified by logically OR'ing together one or more of the following values: *DB_DUP* When creating a new database, this flag enables the storing of duplicate keys in the database. If *DB_DUPSORT* is not specified as well, the duplicates are stored in the order they are created in the database. *DB_DUPSORT* Enables the sorting of duplicate keys in the database. Ignored if *DB_DUP* isn't also specified. Minkey TODO Compare Allow you to override the default sort order used in the database. See `"Changing the sort order"' in this node for an example. sub compare { my ($key, $key2) = @_ ; ... # return 0 if $key1 eq $key2 # -1 if $key1 lt $key2 # 1 if $key1 gt $key2 return (-1 , 0 or 1) ; } tie %h, "BerkeleyDB::Hash", -Filename => $filename, -Compare => \&compare, ... Prefix sub prefix { my ($key, $key2) = @_ ; ... # return number of bytes of $key2 which are # necessary to determine that it is greater than $key1 return $bytes ; } tie %h, "BerkeleyDB::Hash", -Filename => $filename, -Prefix => \&prefix, ... =item DupCompare sub compare { my ($key, $key2) = @_ ; ... # return 0 if $key1 eq $key2 # -1 if $key1 lt $key2 # 1 if $key1 gt $key2 return (-1 , 0 or 1) ; } tie %h, "BerkeleyDB::Hash", -Filename => $filename, -DupCompare => \&compare, ... Methods ------- BerkeleyDB::Btree supports the following database methods. See also `COMMON DATABASE METHODS' in this node. All the methods below return 0 to indicate success. $status = $db->db_key_range($key, $less, $equal, $greater [, $flags]) Given a key, $key, this method returns the proportion of keys less than $key in `$less', the proportion equal to $key in `$equal' and the proportion greater than $key in `$greater'. The proportion is returned as a double in the range 0.0 to 1.0. A Simple Btree Example ---------------------- The code below is a simple example of using a btree database. use strict ; use BerkeleyDB ; my $filename = "tree" ; unlink $filename ; my %h ; tie %h, 'BerkeleyDB::Btree', -Filename => $filename, -Flags => DB_CREATE or die "Cannot open $filename: $!\n" ; # Add a key/value pair to the file $h{'Wall'} = 'Larry' ; $h{'Smith'} = 'John' ; $h{'mouse'} = 'mickey' ; $h{'duck'} = 'donald' ; # Delete delete $h{"duck"} ; # Cycle through the keys printing them in order. # Note it is not necessary to sort the keys as # the btree will have kept them in order automatically. foreach (keys %h) { print "$_\n" } untie %h ; Here is the output from the code above. The keys have been sorted using Berkeley DB's default sorting algorithm. Smith Wall mouse Changing the sort order ----------------------- It is possible to supply your own sorting algorithm if the one that Berkeley DB used isn't suitable. The code below is identical to the previous example except for the case insensitive compare function. use strict ; use BerkeleyDB ; my $filename = "tree" ; unlink $filename ; my %h ; tie %h, 'BerkeleyDB::Btree', -Filename => $filename, -Flags => DB_CREATE, -Compare => sub { lc $_[0] cmp lc $_[1] } or die "Cannot open $filename: $!\n" ; # Add a key/value pair to the file $h{'Wall'} = 'Larry' ; $h{'Smith'} = 'John' ; $h{'mouse'} = 'mickey' ; $h{'duck'} = 'donald' ; # Delete delete $h{"duck"} ; # Cycle through the keys printing them in order. # Note it is not necessary to sort the keys as # the btree will have kept them in order automatically. foreach (keys %h) { print "$_\n" } untie %h ; Here is the output from the code above. mouse Smith Wall There are a few point to bear in mind if you want to change the ordering in a BTREE database: 1. The new compare function must be specified when you create the database. 2. You cannot change the ordering once the database has been created. Thus you must use the same compare function every time you access the database. Using db_stat ------------- TODO BerkeleyDB::Recno ================= Equivalent to calling *db_open* with type DB_RECNO in Berkeley DB 2.x and calling *db_create* followed by *DB->open* with type DB_RECNO in Berkeley DB 3.x. Two forms of constructor are supported: $db = new BerkeleyDB::Recno [ -Filename => "filename", ] [ -Subname => "sub-database name", ] [ -Flags => flags,] [ -Property => flags,] [ -Mode => number,] [ -Cachesize => number,] [ -Lorder => number,] [ -Pagesize => number,] [ -Env => $env,] [ -Txn => $txn,] # BerkeleyDB::Recno specific [ -Delim => byte,] [ -Len => number,] [ -Pad => byte,] [ -Source => filename,] and this [$db =] tie @arry, 'BerkeleyDB::Recno', [ -Filename => "filename", ] [ -Subname => "sub-database name", ] [ -Flags => flags,] [ -Property => flags,] [ -Mode => number,] [ -Cachesize => number,] [ -Lorder => number,] [ -Pagesize => number,] [ -Env => $env,] [ -Txn => $txn,] # BerkeleyDB::Recno specific [ -Delim => byte,] [ -Len => number,] [ -Pad => byte,] [ -Source => filename,] A Recno Example --------------- Here is a simple example that uses RECNO (if you are using a version of Perl earlier than 5.004_57 this example won't work - see `Extra RECNO Methods' in this node for a workaround). use strict ; use BerkeleyDB ; my $filename = "text" ; unlink $filename ; my @h ; tie @h, 'BerkeleyDB::Recno', -Filename => $filename, -Flags => DB_CREATE, -Property => DB_RENUMBER or die "Cannot open $filename: $!\n" ; # Add a few key/value pairs to the file $h[0] = "orange" ; $h[1] = "blue" ; $h[2] = "yellow" ; push @h, "green", "black" ; my $elements = scalar @h ; print "The array contains $elements entries\n" ; my $last = pop @h ; print "popped $last\n" ; unshift @h, "white" ; my $first = shift @h ; print "shifted $first\n" ; # Check for existence of a key print "Element 1 Exists with value $h[1]\n" if $h[1] ; untie @h ; Here is the output from the script: The array contains 5 entries popped black shifted white Element 1 Exists with value blue The last element is green The 2nd last element is yellow BerkeleyDB::Queue ================= Equivalent to calling *db_create* followed by *DB->open* with type *DB_QUEUE* in Berkeley DB 3.x. This database format isn't available if you use Berkeley DB 2.x. Two forms of constructor are supported: $db = new BerkeleyDB::Queue [ -Filename => "filename", ] [ -Subname => "sub-database name", ] [ -Flags => flags,] [ -Property => flags,] [ -Mode => number,] [ -Cachesize => number,] [ -Lorder => number,] [ -Pagesize => number,] [ -Env => $env,] [ -Txn => $txn,] # BerkeleyDB::Queue specific [ -Len => number,] [ -Pad => byte,] [ -ExtentSize => number, ] and this [$db =] tie @arry, 'BerkeleyDB::Queue', [ -Filename => "filename", ] [ -Subname => "sub-database name", ] [ -Flags => flags,] [ -Property => flags,] [ -Mode => number,] [ -Cachesize => number,] [ -Lorder => number,] [ -Pagesize => number,] [ -Env => $env,] [ -Txn => $txn,] # BerkeleyDB::Queue specific [ -Len => number,] [ -Pad => byte,] BerkeleyDB::Unknown =================== This class is used to open an existing database. Equivalent to calling *db_open* with type *DB_UNKNOWN* in Berkeley DB 2.x and calling *db_create* followed by *DB->open* with type *DB_UNKNOWN* in Berkeley DB 3.x. The constructor looks like this: $db = new BerkeleyDB::Unknown [ -Filename => "filename", ] [ -Subname => "sub-database name", ] [ -Flags => flags,] [ -Property => flags,] [ -Mode => number,] [ -Cachesize => number,] [ -Lorder => number,] [ -Pagesize => number,] [ -Env => $env,] [ -Txn => $txn,] An example ---------- COMMON OPTIONS ============== All database access class constructors support the common set of options defined below. All are optional. -Filename The database filename. If no filename is specified, a temporary file will be created and removed once the program terminates. -Subname Specifies the name of the sub-database to open. This option is only valid if you are using Berkeley DB 3.x. -Flags Specify how the database will be opened/created. The valid flags are: *DB_CREATE* Create any underlying files, as necessary. If the files do not already exist and the *DB_CREATE* flag is not specified, the call will fail. *DB_NOMMAP* Not supported by BerkeleyDB. *DB_RDONLY* Opens the database in read-only mode. *DB_THREAD* Not supported by BerkeleyDB. *DB_TRUNCATE* If the database file already exists, remove all the data before opening it. -Mode Determines the file protection when the database is created. Defaults to 0666. -Cachesize -Lorder -Pagesize -Env When working under a Berkeley DB environment, this parameter Defaults to no environment. -Txn TODO. COMMON DATABASE METHODS ======================= All the database interfaces support the common set of methods defined below. All the methods below return 0 to indicate success. $status = $db->db_get($key, $value [, $flags]) ---------------------------------------------- Given a key ($key) this method reads the value associated with it from the database. If it exists, the value read from the database is returned in the $value parameter. The $flags parameter is optional. If present, it must be set to one of the following values: DB_GET_BOTH When the DB_GET_BOTH flag is specified, *db_get* checks for the existence of both the $key and $value in the database. DB_SET_RECNO TODO. In addition, the following value may be set by logically OR'ing it into the $flags parameter: DB_RMW TODO $status = $db->db_put($key, $value [, $flags]) ---------------------------------------------- Stores a key/value pair in the database. The $flags parameter is optional. If present it must be set to one of the following values: DB_APPEND This flag is only applicable when accessing a BerkeleyDB::Recno database. TODO. DB_NOOVERWRITE If this flag is specified and $key already exists in the database, the call to *db_put* will return *DB_KEYEXIST*. $status = $db->db_del($key [, $flags]) -------------------------------------- Deletes a key/value pair in the database associated with $key. If duplicate keys are enabled in the database, *db_del* will delete all key/value pairs with key $key. The $flags parameter is optional and is currently unused. $status = $db->db_sync() ------------------------ If any parts of the database are in memory, write them to the database. $cursor = $db->db_cursor([$flags]) ---------------------------------- Creates a cursor object. This is used to access the contents of the database sequentially. See `CURSORS' in this node for details of the methods available when working with cursors. The $flags parameter is optional. If present it must be set to one of the following values: DB_RMW TODO. ($flag, $old_offset, $old_length) = $db->partial_set($offset, $length) ; ------------------------------------------------------------------------ TODO ($flag, $old_offset, $old_length) = $db->partial_clear() ; ---------------------------------------------------------- TODO $db->byteswapped() ------------------ TODO $db->type() ----------- Returns the type of the database. The possible return code are DB_HASH for a BerkeleyDB::Hash database, DB_BTREE for a BerkeleyDB::Btree database and DB_RECNO for a BerkeleyDB::Recno database. This method is typically used when a database has been opened with BerkeleyDB::Unknown. $ref = $db->db_stat() Returns a reference to an associative array containing information about the database. The keys of the associative array correspond directly to the names of the fields defined in the Berkeley DB documentation. For example, in the DB documentation, the field *bt_version* stores the version of the Btree database. Assuming you called *db_stat* on a Btree database the equivalent field would be accessed as follows: $version = $ref->{'bt_version'} ; If you are using Berkeley DB 3.x, this method will work will all database formats. When DB 2.x is used, it only works with BerkeleyDB::Btree. $status = $db->status() ----------------------- Returns the status of the last $db method called. CURSORS ======= A cursor is used whenever you want to access the contents of a database in sequential order. A cursor object is created with the `db_cursor' A cursor object has the following methods available: $newcursor = $cursor->c_dup($flags) ----------------------------------- Creates a duplicate of `$cursor'. This method needs Berkeley DB 3.0.x or better. The $flags parameter is optional and can take the following value: DB_POSITION When present this flag will position the new cursor at the same place as the existing cursor. $status = $cursor->c_get($key, $value, $flags) ---------------------------------------------- Reads a key/value pair from the database, returning the data in $key and $value. The key/value pair actually read is controlled by the $flags parameter, which can take one of the following values: DB_FIRST Set the cursor to point to the first key/value pair in the database. Return the key/value pair in $key and $value. DB_LAST Set the cursor to point to the last key/value pair in the database. Return the key/value pair in $key and $value. DB_NEXT If the cursor is already pointing to a key/value pair, it will be incremented to point to the next key/value pair and return its contents. If the cursor isn't initialised, DB_NEXT works just like DB_FIRST. If the cursor is already positioned at the last key/value pair, *c_get* will return *DB_NOTFOUND*. DB_NEXT_DUP This flag is only valid when duplicate keys have been enabled in a database. If the cursor is already pointing to a key/value pair and the key of the next key/value pair is identical, the cursor will be incremented to point to it and their contents returned. DB_PREV If the cursor is already pointing to a key/value pair, it will be decremented to point to the previous key/value pair and return its contents. If the cursor isn't initialised, DB_PREV works just like DB_LAST. If the cursor is already positioned at the first key/value pair, *c_get* will return *DB_NOTFOUND*. DB_CURRENT If the cursor has been set to point to a key/value pair, return their contents. If the key/value pair referenced by the cursor has been deleted, *c_get* will return *DB_KEYEMPTY*. DB_SET Set the cursor to point to the key/value pair referenced by $key and return the value in $value. DB_SET_RANGE This flag is a variation on the DB_SET flag. As well as returning the value, it also returns the key, via $key. When used with a BerkeleyDB::Btree database the key matched by *c_get* will be the shortest key (in length) which is greater than or equal to the key supplied, via $key. This allows partial key searches. See ??? for an example of how to use this flag. DB_GET_BOTH Another variation on DB_SET. This one returns both the key and the value. DB_SET_RECNO TODO. DB_GET_RECNO TODO. In addition, the following value may be set by logically OR'ing it into the $flags parameter: DB_RMW TODO. $status = $cursor->c_put($key, $value, $flags) ---------------------------------------------- Stores the key/value pair in the database. The position that the data is stored in the database is controlled by the $flags parameter, which must take one of the following values: DB_AFTER When used with a Btree or Hash database, a duplicate of the key referenced by the current cursor position will be created and the contents of $value will be associated with it - $key is ignored. The new key/value pair will be stored immediately after the current cursor position. Obviously the database has to have been opened with *DB_DUP*. When used with a Recno ... TODO DB_BEFORE When used with a Btree or Hash database, a duplicate of the key referenced by the current cursor position will be created and the contents of $value will be associated with it - $key is ignored. The new key/value pair will be stored immediately before the current cursor position. Obviously the database has to have been opened with *DB_DUP*. When used with a Recno ... TODO DB_CURRENT If the cursor has been initialised, replace the value of the key/value pair stored in the database with the contents of $value. DB_KEYFIRST Only valid with a Btree or Hash database. This flag is only really used when duplicates are enabled in the database and sorted duplicates haven't been specified. In this case the key/value pair will be inserted as the first entry in the duplicates for the particular key. DB_KEYLAST Only valid with a Btree or Hash database. This flag is only really used when duplicates are enabled in the database and sorted duplicates haven't been specified. In this case the key/value pair will be inserted as the last entry in the duplicates for the particular key. $status = $cursor->c_del([$flags]) ---------------------------------- This method deletes the key/value pair associated with the current cursor position. The cursor position will not be changed by this operation, so any subsequent cursor operation must first initialise the cursor to point to a valid key/value pair. If the key/value pair associated with the cursor have already been deleted, *c_del* will return *DB_KEYEMPTY*. The $flags parameter is not used at present. $status = $cursor->c_del($cnt [, $flags]) ----------------------------------------- Stores the number of duplicates at the current cursor position in *$cnt*. The $flags parameter is not used at present. This method needs Berkeley DB 3.1 or better. $status = $cursor->status() --------------------------- Returns the status of the last cursor method as a dual type. Cursor Examples --------------- TODO Iterating from first to last, then in reverse. examples of each of the flags. JOIN ==== Join support for BerkeleyDB is in progress. Watch this space. TODO TRANSACTIONS ============ TODO. DBM Filters =========== A DBM Filter is a piece of code that is be used when you always want to make the same transformation to all keys and/or values in a DBM database. All of the database classes (BerkeleyDB::Hash, BerkeleyDB::Btree and BerkeleyDB::Recno) support DBM Filters. There are four methods associated with DBM Filters. All work identically, and each is used to install (or uninstall) a single DBM Filter. Each expects a single parameter, namely a reference to a sub. The only difference between them is the place that the filter is installed. To summarise: filter_store_key If a filter has been installed with this method, it will be invoked every time you write a key to a DBM database. filter_store_value If a filter has been installed with this method, it will be invoked every time you write a value to a DBM database. filter_fetch_key If a filter has been installed with this method, it will be invoked every time you read a key from a DBM database. filter_fetch_value If a filter has been installed with this method, it will be invoked every time you read a value from a DBM database. You can use any combination of the methods, from none, to all four. All filter methods return the existing filter, if present, or undef in not. To delete a filter pass undef to it. The Filter ---------- When each filter is called by Perl, a local copy of $_ will contain the key or value to be filtered. Filtering is achieved by modifying the contents of $_. The return code from the filter is ignored. An Example - the NULL termination problem. ------------------------------------------ Consider the following scenario. You have a DBM database that you need to share with a third-party C application. The C application assumes that all keys and values are NULL terminated. Unfortunately when Perl writes to DBM databases it doesn't use NULL termination, so your Perl application will have to manage NULL termination itself. When you write to the database you will have to use something like this: $hash{"$key\0"} = "$value\0" ; Similarly the NULL needs to be taken into account when you are considering the length of existing keys/values. It would be much better if you could ignore the NULL terminations issue in the main application code and have a mechanism that automatically added the terminating NULL to all keys and values whenever you write to the database and have them removed when you read from the database. As I'm sure you have already guessed, this is a problem that DBM Filters can fix very easily. use strict ; use BerkeleyDB ; my %hash ; my $filename = "filt.db" ; unlink $filename ; my $db = tie %hash, 'BerkeleyDB::Hash', -Filename => $filename, -Flags => DB_CREATE or die "Cannot open $filename: $!\n" ; # Install DBM Filters $db->filter_fetch_key ( sub { s/\0$// } ) ; $db->filter_store_key ( sub { $_ .= "\0" } ) ; $db->filter_fetch_value( sub { s/\0$// } ) ; $db->filter_store_value( sub { $_ .= "\0" } ) ; $hash{"abc"} = "def" ; my $a = $hash{"ABC"} ; # ... undef $db ; untie %hash ; Hopefully the contents of each of the filters should be self-explanatory. Both "fetch" filters remove the terminating NULL, and both "store" filters add a terminating NULL. Another Example - Key is a C int. --------------------------------- Here is another real-life example. By default, whenever Perl writes to a DBM database it always writes the key and value as strings. So when you use this: $hash{12345} = "something" ; the key 12345 will get stored in the DBM database as the 5 byte string "12345". If you actually want the key to be stored in the DBM database as a C int, you will have to use pack when writing, and unpack when reading. Here is a DBM Filter that does it: use strict ; use BerkeleyDB ; my %hash ; my $filename = "filt.db" ; unlink $filename ; my $db = tie %hash, 'BerkeleyDB::Btree', -Filename => $filename, -Flags => DB_CREATE or die "Cannot open $filename: $!\n" ; $db->filter_fetch_key ( sub { $_ = unpack("i", $_) } ) ; $db->filter_store_key ( sub { $_ = pack ("i", $_) } ) ; $hash{123} = "def" ; # ... undef $db ; untie %hash ; This time only two filters have been used - we only need to manipulate the contents of the key, so it wasn't necessary to install any value filters. Using BerkeleyDB with MLDBM =========================== Both BerkeleyDB::Hash and BerkeleyDB::Btree can be used with the MLDBM module. The code fragment below shows how to open associate MLDBM with BerkeleyDB::Btree. To use BerkeleyDB::Hash just replace BerkeleyDB::Btree with BerkeleyDB::Hash. use strict ; use BerkeleyDB ; use MLDBM qw(BerkeleyDB::Btree) ; use Data::Dumper; my $filename = 'testmldbm' ; my %o ; unlink $filename ; tie %o, 'MLDBM', -Filename => $filename, -Flags => DB_CREATE or die "Cannot open database '$filename: $!\n"; See the MLDBM documentation for information on how to use the module and for details of its limitations. EXAMPLES ======== TODO. HINTS & TIPS ============ Sharing Databases With C Applications ------------------------------------- There is no technical reason why a Berkeley DB database cannot be shared by both a Perl and a C application. The vast majority of problems that are reported in this area boil down to the fact that C strings are NULL terminated, whilst Perl strings are not. See `An Example -- the NULL termination problem.' in this node in the DBM FILTERS section for a generic way to work around this problem. The untie Gotcha ---------------- TODO COMMON QUESTIONS ================ This section attempts to answer some of the more common questions that I get asked. Relationship with DB_File ------------------------- Before Berkeley DB 2.x was written there was only one Perl module that interfaced to Berkeley DB. That module is called DB_File. Although DB_File can be build with Berkeley DB 1.x, 2.x or 3.x, it only provides an interface to the functionality available in Berkeley DB 1.x. That means that it doesn't support transactions, locking or any of the other new features available in DB 2.x or 3.x. How do I store Perl data structures with BerkeleyDB? ---------------------------------------------------- See `Using BerkeleyDB with MLDBM' in this node. HISTORY ======= See the Changes file. AVAILABILITY ============ The most recent version of *BerkeleyDB* can always be found on CPAN (see `CPAN', *Note Perlmod: (perl.info)perlmod, for details), in the directory `modules/by-module/BerkeleyDB'. The official web site for Berkeley DB is `http://www.sleepycat.com'. COPYRIGHT ========= Copyright (c) 1997-2001 Paul Marquess. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Although *BerkeleyDB* is covered by the Perl license, the library it makes use of, namely Berkeley DB, is not. Berkeley DB has its own copyright and its own license. Please take the time to read it. Here are few words taken from the Berkeley DB FAQ (at `http://www.sleepycat.com') regarding the license: Do I have to license DB to use it in Perl scripts? No. The Berkeley DB license requires that software that uses Berkeley DB be freely redistributable. In the case of Perl, that software is Perl, and not your scripts. Any Perl scripts that you write are your property, including scripts that make use of Berkeley DB. Neither the Perl license nor the Berkeley DB license place any restriction on what you may do with them. If you are in any doubt about the license situation, contact either the Berkeley DB authors or the author of BerkeleyDB. See `"AUTHOR"' in this node for details. AUTHOR ====== Paul Marquess . Questions about Berkeley DB may be addressed to . SEE ALSO ======== perl(1), DB_File, Berkeley DB.