GDBM_File(3perl)
π GDBM_File(3perl) β Perl Programmers Reference Guide π
okay bestie, sit down, hydrate, we're doing databases today π«Ά
β¨ NAME β¨
GDBM_File β Perl5 access to the gdbm library. no cap, that's literally it, that's the whole vibe πΈ
π₯ SYNOPSIS π₯
use GDBM_File;
[$db =] tie %hash, 'GDBM_File', $filename, GDBM_WRCREAT, 0640
or die "$GDBM_File::gdbm_errno";
# Use the %hash...
$e = $db->errno;
$e = $db->syserrno;
$str = $db->strerror;
$bool = $db->needs_recovery;
$db->clear_error;
$db->reorganize;
$db->sync;
$n = $db->count;
$n = $db->flags;
$str = $db->dbname;
$db->cache_size;
$db->cache_size($newsize);
$n = $db->block_size;
$bool = $db->sync_mode;
$db->sync_mode($bool);
$bool = $db->centfree;
$db->centfree($bool);
$bool = $db->coalesce;
$db->coalesce($bool);
$bool = $db->mmap;
$size = $db->mmapsize;
$db->mmapsize($newsize);
$db->recover(%args);
untie %hash ;
look at all those methods. she's got range π
π DESCRIPTION π
So. GDBM_File is the module that lets your Perl programs use all the fancy facilities of the GNU gdbm library. fr fr. If you're actually planning to use this thing, you should really have a copy of the GDBM manual next to you β it lives online at <https://www.gnu.org.ua/software/gdbm/manual>.
Most of the gdbm functions are available through the GDBM_File interface. iconic behavior, we love to see it β¨
β οΈ okay this part is important, don't skip it β οΈ
Unlike Perl's built-in hashes, it is not safe to delete the current item from a GDBM_File tied hash while iterating over it with each. That is a limitation of the gdbm library, not a skill issue, not your fault, it's just how she is π
π Tie π
Use the Perl built-in tie to associate a GDBM database with a Perl hash:
tie %hash, 'GDBM_File', $filename, $flags, $mode;
Here's the breakdown babes:
$filenameis the name of the database file to open or create.$flagsis a bitwise OR of an access mode and some optional modifiers.- access mode is one of these four π
access modes
GDBM_READERβ opens an already-existing database file in read-only mode. look, don't touch πGDBM_WRITERβ opens an already-existing database file in read-write mode.GDBM_WRCREATβ if the database file exists, opens it read-write. If it doesn't exist, creates it first and then opens it read-write. she's flexible πGDBM_NEWDBβ creates a new database and opens it read-write. And if the database already exists? truncates it first. gone. deleted. periodt π
modifiers
A number of modifiers can be OR'd onto the access mode. Most of them are rarely needed (peep <https://www.gnu.org.ua/software/gdbm/manual/Open.html> for the complete list), but one is worth mentioning:
GDBM_NUMSYNCβ when you use this withGDBM_NEWDB, it instructs GDBM to create the database in extended (so called numsync) format. This format is best suited for crash-tolerant implementations. Scroll down to CRASH TOLERANCE for more info πΈ
the mode parameter
The $mode parameter is the file mode for creating a new database file. Use an octal constant, or a combination of S_I* constants from the Fcntl module. This parameter gets used if $flags is GDBM_NEWDB or GDBM_WRCREAT.
what you get back
On success, tie returns an object of class GDBM_File. On failure, it returns undef. And bestie, please β always check the return value, so you actually know your hash got associated with the database file. See ERROR HANDLING below for examples π«Ά
π¦ STATIC METHODS π¦
GDBM_version
$str = GDBM_File->GDBM_version;
@ar = GDBM_File->GDBM_version;
Returns the version number of the underlying libgdbm library. β¨
In scalar context, it returns the library version formatted as a string:
MINOR.MAJOR[.PATCH][ (GUESS)]
where MINOR, MAJOR, and PATCH are version numbers, and GUESS is a guess level (more on that below π).
In list context, it returns a list:
( MINOR, MAJOR, PATCH [, GUESS] )
The GUESS component is present only if the libgdbm version is 1.8.3 or earlier. Why? Because earlier releases of libgdbm didn't include information about their version, so the GDBM_File module has to do certain guesswork in order to figure it out π. GUESS is a textual description in string context, and a positive number indicating how rough the guess is in list context. Possible values are:
1β exact guess. The major and minor version numbers are guaranteed to be correct. The actual patchlevel is most probably guessed right, but can be 1-2 less than indicated.2β approximate. The major and minor number are guaranteed to be correct. The patchlevel is set to the upper bound.3β rough guess. The version is guaranteed to be not newer thanMAJOR.MINOR.
π ERROR HANDLING π
$GDBM_File::gdbm_errno
When referenced in numeric context, retrieves the current value of the gdbm_errno variable β that is, a numeric code describing the state of the most recent operation on any gdbm database. Every numeric code has a symbolic name associated with it. For a comprehensive list of these, see <https://www.gnu.org.ua/software/gdbm/manual/Error-codes.html>.
π heads up: that list includes all error codes defined for the most recent version of gdbm. Depending on the actual version of the library GDBM_File is built with, some of these may be missing. so don't come for her if one's absent π
In string context, $gdbm_errno returns a human-readable description of the error. If necessary, that description includes the value of $!. Which means you can just drop it into diagnostic messages, slay. For example, the usual tying sequence is:
tie %hash, 'GDBM_File', $filename, GDBM_WRCREAT, 0640
or die "$GDBM_File::gdbm_errno";
Here's a more complex one, showing how you can fall back to read-only mode if the database file permissions forbid read-write access:
use Errno qw(EACCES);
unless (tie(%hash, 'GDBM_File', $filename, GDBM_WRCREAT, 0640)) {
if ($GDBM_File::gdbm_errno == GDBM_FILE_OPEN_ERROR
&& $!{EACCES}) {
if (tie(%hash, 'GDBM_File', $filename, GDBM_READER, 0640)) {
die "$GDBM_File::gdbm_errno";
}
} else {
die "$GDBM_File::gdbm_errno";
}
}
see? resilience. main character energy π
gdbm_check_syserr
if (gdbm_check_syserr(gdbm_errno)) ...
Returns true if the system error number ($!) gives more information on the cause of the error. like, "this isn't just vibes, the OS has opinions" π
DATABASE METHODS π
Vibe check bestie: we're now in the DATABASE METHODS section. These methods are giving main character energy. They're the moves you pull on your $db object after you've tied your hash. Let's get into it. No cap. π«Ά
close π
Signature:
$db->close;
Okay so this closes the database. Normally you'd just do untie and call it a day. But here's the tea: if you explicitly assigned the result of tie to a variable, and you wanna release the database to another user, you need this. Consider this code:
$db = tie %hash, 'GDBM_File', $filename, GDBM_WRCREAT, 0640;
# Do something with %hash or $db...
untie %hash;
$db->close;
In this example, doing untie alone is not enough. The way that $db still references the database means the database file would remain locked. Calling $db->close ensures the database file is closed and unlocked. Periodt. π
errno π
Signature: $db->errno
Returns the last error status associated with this database. In string context, returns a human-readable description of the error. See also $GDBM_File::gdbm_errno variable above (we talked about that in the previous part, iykyk). β¨
syserrno π
Signature: $db->syserrno
Returns the last system error status (C "errno" variable), associated with this database. (Yes, there's a comma in the original, we keep it.) π
strerror π
Signature: $db->strerror
Returns textual description of the last error that occurred in this database. So you can actually read what went wrong. Iconic. π
clear_error π§Ή
Signature: $db->clear_error
Clear error status. Like wiping the slate clean. β¨
needs_recovery π
Signature: $db->needs_recovery
Returns true if the database needs recovery. So if it's giving damaged vibes, this tells you. π
reorganize π§Ή
Signature: $db->reorganize;
Reorganizes the database. Like cleaning your room but for data. π§
sync π
Signature: $db->sync;
Synchronizes recent changes to the database with its disk copy. So everything's on the same page. π
count π’
Signature: $n = $db->count;
Returns number of keys in the database. So you know how many besties are in the club. π
flags π©
Signature: $db->flags;
Returns flags passed as 4th argument to tie. You know, those GDBM_WRCREAT type things. π³οΈ
dbname π
Signature: $db->dbname;
Returns the database name (i.e. 3rd argument to tie). So the filename you gave it. π
cache_size π¦
Signatures:
$db->cache_size;
$db->cache_size($newsize);
Returns the size of the internal GDBM cache for that database. Called with argument, sets the size to $newsize. So you can check or change how much memory it's using for cache. πΎ
block_size π§±
Signature: $db->block_size;
Returns the block size of the database. It's giving very technical, but okay. π
sync_mode π
Signatures:
$db->sync_mode;
$db->sync_mode($bool);
Returns the status of the automatic synchronization mode. Called with argument, enables or disables the sync mode, depending on whether $bool is true or false.
When synchronization mode is on (true), any changes to the database are immediately written to the disk. This ensures database consistency in case of any unforeseen errors (e.g. power failures), at the expense of considerable slowdown of operation. So it's safe but slow. π
Synchronization mode is off by default. So you gotta turn it on if you want that extra safety. π‘οΈ
centfree π―
Signatures:
$db->centfree;
$db->centfree($bool);
Returns status of the central free block pool (0 - disabled, 1 - enabled). With argument, changes its status. By default, central free block pool is disabled. So lowkey off unless you say otherwise. π
coalesce π€
Signatures:
$db->coalesce;
$db->coalesce($bool);
Original doesn't give a description, just the signatures. So we're keeping it real: it takes an optional $bool. That's all we know. π€·ββοΈ
mmap πΊοΈ
Signature: $db->mmap;
Returns true if memory mapping is enabled. This method will highkey croak if the libgdbm library is compiled without memory mapping support. So if it's not built with mmap, it'll throw hands. π€
mmapsize π
Signatures:
$db->mmapsize;
$db->mmapsize($newsize);
If memory mapping is enabled, returns the size of memory mapping. With argument, sets the size to $newsize. This method will croak if the libgdbm library is compiled without memory mapping support. Same deal as above. πΊοΈ
recover π
Signature: $db->recover(%args);
Recovers data from a failed database. %args is optional and can contain following keys:
err => sub { ... }β Reference to code for detailed error reporting. Upon encountering an error,recoverwill call this sub with a single argument - a description of the error.backup => \$strβ Creates a backup copy of the database before recovery and returns its filename in$str.max_failed_keys => $nβ Maximum allowed number of failed keys. If the actual number becomes equal to$n,recoveraborts and returns error.max_failed_buckets => $nβ Maximum allowed number of failed buckets. If the actual number becomes equal to$n,recoveraborts and returns error.max_failures => $nβ Maximum allowed number of failures during recovery.stat => \%hashβ Return recovery statistics in%hash. Upon return, the following keys will be present:recovered_keysβ Number of successfully recovered keys.recovered_bucketsβ Number of successfully recovered buckets.failed_keysβ Number of keys that failed to be retrieved.failed_bucketsβ Number of buckets that failed to be retrieved.
convert π
Signature: $db->convert($format);
Changes the format of the database file referred to by $db.
Starting from version 1.20, gdbm supports two database file formats: standard and extended. The former is the traditional database format, used by previous gdbm versions. The extended format contains additional data and is recommended for use in crash tolerant applications.
<https://www.gnu.org.ua/software/gdbm/manual/Numsync.html>, for the discussion of both formats. (Just dropping the URL, no link, periodt.)
The $format argument sets the new desired database format. It is GDBM_NUMSYNC to convert the database from standard to extended format, and 0 to convert it from extended to standard format.
If the database is already in the requested format, the function returns success without doing anything. So no unnecessary work. π
dump π€
Signature: $db->dump($filename, %options)
Creates a dump of the database file in $filename. Such file can be used as a backup copy or sent over a wire to recreate the database on another machine. To create a database from the dump file, use the load method.
GDBM supports two dump formats: old binary and new ascii. The binary format is not portable across architectures and is deprecated. It is supported for backward compatibility. The ascii format is portable and stores additional meta-data about the file. It was introduced with the gdbm version 1.11 and is the preferred dump format. The dump method creates ascii dumps by default.
If the named file already exists, the function will refuse to overwrite and will croak an error. If it doesn't exist, it will be created with the mode 0666 modified by the current umask.
These defaults can be altered using the following %options:
binary => 1β Create dump in binary format.mode => MODEβ Set file mode toMODE.overwrite => 1β Silently overwrite existing files.
load π₯
Signature: $db->load($filename, %options)
Load the data from the dump file $filename into the database $db. The file must have been previously created using the dump method. File format is recognized automatically. By default, the function will croak if the dump contains a key that already exists in the database. It will silently ignore the failure to restore database mode and/or ownership.
These defaults can be altered using the following %options:
replace => 1β Replace existing keys.restore_mode => 0 | 1β If 0, don't try to restore the mode of the database file to that stored in the dump.restore_owner => 0 | 1β If 0, don't try to restore the owner of the database file to that stored in the dump.strict_errors => 1β Croak if failed to restore ownership and/or mode.
The usual sequence to recreate a database from the dump file is:
my %hash;
my $db = tie %hash, 'GDBM_File', 'a.db', GDBM_NEWDB, 0640;
$db->load('a.dump');
π₯ CRASH TOLERANCE π₯
Okay so this one is genuinely the coolest part of the whole page, bestie. Crash tolerance is a feature that β if your OS and your filesystem are willing to play along β makes it so that after a crash (power outage, OS kernel panic, the laptop falling off the bed, whatever π) you can recover a logically consistent recent state of the database. It's giving time machine energy. β³β¨
This whole thing showed up in gdbm version 1.21. The theory behind it lives in "Crashproofing the Original NoSQL Key-Value Store" by Terence Kelly (https://queue.acm.org/detail.cfm?id=3487353), and if you want the deep gdbm implementation tea π΅ it's all in the GDBM Manual (https://www.gnu.org.ua/software/gdbm/manual/Crash-Tolerance.html). Everything down below is about the Perl interface specifically, k?
For maximum robustness (like, the most slay possible π‘οΈ) we recommend you use the extended database format for crash tolerant databases. Want a database in extended format from the jump? Pass GDBM_NEWDB|GDBM_NUMSYNC when you open it, like:
$db = tie %hash, 'GDBM_File', $filename,
GDBM_NEWDB|GDBM_NUMSYNC, 0640;
And if you already have a database living its standard-format life and you wanna glow it up into extended format, hit the convert method (yeah, the one we covered earlier π):
$db->convert(GDBM_NUMSYNC);
π©Ί crash_tolerance_status π©Ί
GDBM_File->crash_tolerance_status;
Static method, returns the status of crash tolerance support. A non-zero value means crash tolerance is compiled in and the operating system is actually down for it. A zero means... it's not. π
π― failure_atomic π―
$db->failure_atomic($even, $odd)
This turns on crash tolerance for the database $db. The arguments are the pathnames of two files that are gonna get created and filled with snapshots of the database file. Important things, no cap:
- Both files must not exist when you call this method.
- Both files must live on the same filesystem as the database file.
- That filesystem has to support the reflink operation (
https://www.gnu.org.ua/software/gdbm/manual/Filesystems-supporting-crash-tolerance.html).
After failure_atomic succeeds, every single call to the $db->sync method makes an efficient reflink snapshot of the database file into one of those two files. And the consecutive calls to sync alternate between the two β hence the names $even and $odd. Cute, right? π Back and forth, back and forth, like a little pendulum.
The most recent of those files is what you use to recover the database after a crash. To pick the right snapshot, use the latest_snapshot static method. π΅οΈββοΈ
π latest_snapshot π
$file = GDBM_File->latest_snapshot($even, $odd);
($file, $error) = GDBM_File->latest_snapshot($even, $odd);
You hand it the two snapshot names (the exact ones you used earlier in your failure_atomic call), and it picks whichever one is suitable for database recovery β aka the file holding the most recent database snapshot.
- In scalar context, it returns the selected file name, or
undefif something went wrong. - In array context, it returns a list of two elements: the file name and a status code. On success, the file name is defined and the code is
GDBM_SNAPSHOT_OK. On error, the file name isundefand the status is one of these bad boys: GDBM_SNAPSHOT_BADβ Neither snapshot file is applicable. This means the crash happened before a call tofailure_atomiccompleted. In this case, it is best to fall back on a safe backup copy of the data file. π«GDBM_SNAPSHOT_ERRβ A system error occurred. Go examine$!for details. There's a comprehensive list of error codes and their meaning over athttps://www.gnu.org.ua/software/gdbm/manual/Crash-recovery.html.GDBM_SNAPSHOT_SAMEβ The file modes and modification dates of both snapshot files are exactly the same. This can happen only for databases in standard format.GDBM_SNAPSHOT_SUSPICIOUSβ The numsync counters of the two snapshots differ by more than one. Most probable reason? Programmer error, bestie π β the two parameters refer to snapshots belonging to different database files.
π¦ AVAILABILITY π¦
gdbm is available from any GNU archive. The master site is ftp.gnu.org, but you are strongly urged to use one of the many mirrors (seriously, be nice to the master site π₯Ί). You can obtain a list of mirror sites from http://www.gnu.org/order/ftp.html.
π SECURITY AND PORTABILITY π
GDBM files are not portable across platforms. If you wish to transfer a GDBM file over the wire, dump it to a portable format first. π
Do not accept GDBM files from untrusted sources. Like, ever. π«
Robustness of GDBM against corrupted databases depends highly on its version, and this part is important so listen up:
- Versions prior to
1.15did not implement any validity checking at all β so a corrupted or maliciously crafted database file could cause perl to crash or even expose a security vulnerability. π± - Versions between
1.15and1.20were progressively strengthened against invalid inputs. - Version
1.21had undergone extensive fuzzy checking, which proved its ability to withstand any kinds of inputs without crashing. She ate that. π
π SEE ALSO π
And that's the whole page, bestie!! ππ«Ά This lil doc is GDBM_File(3perl) from perl v5.44.0, dated 2026-10-17. Go forth and tie your hashes responsibly. πβ¨π·
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms