📄 db_file.pm
字号:
} die $msg; } die "pos unexpectedly changed from $old_pos to $pos with R_IBEFORE" if $old_pos != $pos; ++ $pos; ++ $num_elems; } if (wantarray) { # 'In list context, returns the elements removed from the # array.' # return @removed; } elsif (defined wantarray and not wantarray) { # 'In scalar context, returns the last element removed, or # undef if no elements are removed.' # if (@removed) { my $last = pop @removed; return "$last"; } else { return undef; } } elsif (not defined wantarray) { # Void context } else { die }}sub ::DB_File::splice { &SPLICE }sub find_dup{ croak "Usage: \$db->find_dup(key,value)\n" unless @_ == 3 ; my $db = shift ; my ($origkey, $value_wanted) = @_ ; my ($key, $value) = ($origkey, 0); my ($status) = 0 ; for ($status = $db->seq($key, $value, R_CURSOR() ) ; $status == 0 ; $status = $db->seq($key, $value, R_NEXT() ) ) { return 0 if $key eq $origkey and $value eq $value_wanted ; } return $status ;}sub del_dup{ croak "Usage: \$db->del_dup(key,value)\n" unless @_ == 3 ; my $db = shift ; my ($key, $value) = @_ ; my ($status) = $db->find_dup($key, $value) ; return $status if $status != 0 ; $status = $db->del($key, R_CURSOR() ) ; return $status ;}sub get_dup{ croak "Usage: \$db->get_dup(key [,flag])\n" unless @_ == 2 or @_ == 3 ; my $db = shift ; my $key = shift ; my $flag = shift ; my $value = 0 ; my $origkey = $key ; my $wantarray = wantarray ; my %values = () ; my @values = () ; my $counter = 0 ; my $status = 0 ; # iterate through the database until either EOF ($status == 0) # or a different key is encountered ($key ne $origkey). for ($status = $db->seq($key, $value, R_CURSOR()) ; $status == 0 and $key eq $origkey ; $status = $db->seq($key, $value, R_NEXT()) ) { # save the value or count number of matches if ($wantarray) { if ($flag) { ++ $values{$value} } else { push (@values, $value) } } else { ++ $counter } } return ($wantarray ? ($flag ? %values : @values) : $counter) ;}1;__END__=head1 NAMEDB_File - Perl5 access to Berkeley DB version 1.x=head1 SYNOPSIS use DB_File; [$X =] tie %hash, 'DB_File', [$filename, $flags, $mode, $DB_HASH] ; [$X =] tie %hash, 'DB_File', $filename, $flags, $mode, $DB_BTREE ; [$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ; $status = $X->del($key [, $flags]) ; $status = $X->put($key, $value [, $flags]) ; $status = $X->get($key, $value [, $flags]) ; $status = $X->seq($key, $value, $flags) ; $status = $X->sync([$flags]) ; $status = $X->fd ; # BTREE only $count = $X->get_dup($key) ; @list = $X->get_dup($key) ; %list = $X->get_dup($key, 1) ; $status = $X->find_dup($key, $value) ; $status = $X->del_dup($key, $value) ; # RECNO only $a = $X->length; $a = $X->pop ; $X->push(list); $a = $X->shift; $X->unshift(list); @r = $X->splice(offset, length, elements); # 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 { ... } ) ; untie %hash ; untie @array ;=head1 DESCRIPTIONB<DB_File> is a module which allows Perl programs to make use of thefacilities provided by Berkeley DB version 1.x (if you have a newerversion of DB, see L<Using DB_File with Berkeley DB version 2 or greater>).It is assumed that you have a copy of the Berkeley DB manual pages athand when reading this documentation. The interface defined heremirrors the Berkeley DB interface closely.Berkeley DB is a C library which provides a consistent interface to anumber of database formats. B<DB_File> provides an interface to allthree of the database types currently supported by Berkeley DB.The file types are:=over 5=item B<DB_HASH>This database type allows arbitrary key/value pairs to be stored in datafiles. This is equivalent to the functionality provided by otherhashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,the files created using DB_HASH are not compatible with any of theother packages mentioned.A default hashing algorithm, which will be adequate for mostapplications, is built into Berkeley DB. If you do need to use your ownhashing algorithm it is possible to write your own in Perl and haveB<DB_File> use it instead.=item B<DB_BTREE>The btree format allows arbitrary key/value pairs to be stored in asorted, balanced binary tree.As with the DB_HASH format, it is possible to provide a user definedPerl routine to perform the comparison of keys. By default, though, thekeys are stored in lexical order.=item B<DB_RECNO>DB_RECNO allows both fixed-length and variable-length flat text filesto be manipulated using the same key/value pair interface as in DB_HASHand DB_BTREE. In this case the key will consist of a record (line)number.=back=head2 Using DB_File with Berkeley DB version 2 or greaterAlthough B<DB_File> is intended to be used with Berkeley DB version 1,it can also be used with version 2, 3 or 4. In this case the interface islimited to the functionality provided by Berkeley DB 1.x. Anywhere theversion 2 or greater interface differs, B<DB_File> arranges for it to worklike version 1. This feature allows B<DB_File> scripts that were builtwith version 1 to be migrated to version 2 or greater without any changes.If you want to make use of the new features available in Berkeley DB2.x or greater, use the Perl module B<BerkeleyDB> instead.B<Note:> The database file format has changed multiple times in BerkeleyDB version 2, 3 and 4. If you cannot recreate your databases, youmust dump any existing databases with either the C<db_dump> or theC<db_dump185> utility that comes with Berkeley DB.Once you have rebuilt DB_File to use Berkeley DB version 2 or greater,your databases can be recreated using C<db_load>. Refer to the Berkeley DBdocumentation for further details.Please read L<"COPYRIGHT"> before using version 2.x or greater of BerkeleyDB with DB_File.=head2 Interface to Berkeley DBB<DB_File> allows access to Berkeley DB files using the tie() mechanismin Perl 5 (for full details, see L<perlfunc/tie()>). This facilityallows B<DB_File> to access Berkeley DB files using either anassociative array (for DB_HASH & DB_BTREE file types) or an ordinaryarray (for the DB_RECNO file type).In addition to the tie() interface, it is also possible to access mostof the functions provided in the Berkeley DB API directly.See L<THE API INTERFACE>.=head2 Opening a Berkeley DB Database FileBerkeley DB uses the function dbopen() to open or create a database.Here is the C prototype for dbopen(): DB* dbopen (const char * file, int flags, int mode, DBTYPE type, const void * openinfo)The parameter C<type> is an enumeration which specifies which of the 3interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.Depending on which of these is actually chosen, the final parameter,I<openinfo> points to a data structure which allows tailoring of thespecific interface method.This interface is handled slightly differently in B<DB_File>. Here isan equivalent call using B<DB_File>: tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;The C<filename>, C<flags> and C<mode> parameters are the directequivalent of their dbopen() counterparts. The final parameter $DB_HASHperforms the function of both the C<type> and C<openinfo> parameters indbopen().In the example above $DB_HASH is actually a pre-defined reference to ahash object. B<DB_File> has three of these pre-defined references.Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.The keys allowed in each of these pre-defined references is limited tothe names used in the equivalent C structure. So, for example, the$DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,C<ffactor>, C<hash>, C<lorder> and C<nelem>. To change one of these elements, just assign to it like this: $DB_HASH->{'cachesize'} = 10000 ;The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO areusually adequate for most applications. If you do need to create extrainstances of these objects, constructors are available for each filetype.Here are examples of the constructors and the valid options availablefor DB_HASH, DB_BTREE and DB_RECNO respectively. $a = new DB_File::HASHINFO ; $a->{'bsize'} ; $a->{'cachesize'} ; $a->{'ffactor'}; $a->{'hash'} ; $a->{'lorder'} ; $a->{'nelem'} ; $b = new DB_File::BTREEINFO ; $b->{'flags'} ; $b->{'cachesize'} ; $b->{'maxkeypage'} ; $b->{'minkeypage'} ; $b->{'psize'} ; $b->{'compare'} ; $b->{'prefix'} ; $b->{'lorder'} ; $c = new DB_File::RECNOINFO ; $c->{'bval'} ; $c->{'cachesize'} ; $c->{'psize'} ; $c->{'flags'} ; $c->{'lorder'} ; $c->{'reclen'} ; $c->{'bfname'} ;The values stored in the hashes above are mostly the direct equivalentof their C counterpart. Like their C counterparts, all are set to adefault values - that means you don't have to set I<all> of thevalues when you only want to change one. Here is an example: $a = new DB_File::HASHINFO ; $a->{'cachesize'} = 12345 ; tie %y, 'DB_File', "filename", $flags, 0777, $a ;A few of the options need extra discussion here. When used, the Cequivalent of the keys C<hash>, C<compare> and C<prefix> store pointersto C functions. In B<DB_File> these keys are used to store referencesto Perl subs. Below are templates for each of the subs: sub hash { my ($data) = @_ ; ... # return the hash value for $data return $hash ; } 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) ; } sub prefix { my ($key, $key2) = @_ ; ... # return number of bytes of $key2 which are # necessary to determine that it is greater than $key1 return $bytes ; }See L<Changing the BTREE sort order> for an example of using theC<compare> template.If you are using the DB_RECNO interface and you intend making use ofC<bval>, you should check out L<The 'bval' Option>.=head2 Default ParametersIt is possible to omit some or all of the final 4 parameters in thecall to C<tie> and let them take default values. As DB_HASH is the mostcommon file format used, the call: tie %A, "DB_File", "filename" ;is equivalent to: tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;It is also possible to omit the filename parameter as well, so thecall: tie %A, "DB_File" ;is equivalent to: tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;See L<In Memory Databases> for a discussion on the use of C<undef>in place of a filename.=head2 In Memory DatabasesBerkeley DB allows the creation of in-memory databases by using NULL(that is, a C<(char *)0> in C) in place of the filename. B<DB_File>uses C<undef> instead of NULL to provide this functionality.=head1 DB_HASHThe DB_HASH file format is probably the most commonly used of the threefile formats that B<DB_File> supports. It is also very straightforwardto use.=head2 A Simple ExampleThis example shows how to create a database, add key/value pairs to thedatabase, delete keys/value pairs and finally how to enumerate thecontents of the database. use warnings ; use strict ; use DB_File ; our (%h, $k, $v) ; unlink "fruit" ; tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0666, $DB_HASH or die "Cannot open file 'fruit': $!\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 -> yellowNote that the like ordinary associative arrays, the order of the keysretrieved is in an apparently random order.=head1 DB_BTREEThe DB_BTREE format is useful when you want to store data in a givenorder. By default the keys will be stored in lexical order, but as youwill see from the example shown in the next section, it is very easy todefine your own sorting function.=head2 Changing the BTREE sort orderThis script shows how to override the default sorting algorithm thatBTREE uses. Instead of using the normal lexical ordering, a caseinsensitive compare function will be used. use warnings ; use strict ; use DB_File ; my %h ; sub Compare { my ($key1, $key2) = @_ ; "\L$key1" cmp "\L$key2" ;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -