GDBM_File(3pm)

πŸ¦‹ GDBM_File πŸ¦‹

okay so welcome to the GDBM_File(3pm) page, straight out of the Perl Programmers Reference Guide, bestie πŸ’– this is the one that lets your Perl code vibe with the GNU gdbm library, and I'm gonna walk you through every single bit of it, no cap.


πŸ’– NAME πŸ’–

GDBM_File β€” Perl5 access to the gdbm library.


✨ 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 ;

like… look at all those methods, she's booked πŸ’…


🌈 DESCRIPTION 🌈

So GDBM_File is the module that lets your Perl programs use all the facilities the GNU gdbm library hands out. And listen β€” if you're actually gonna use this thing, you really should have a copy of the GDBM manual sitting next to you. It's available online at <https://www.gnu.org.ua/software/gdbm/manual>.

Most of the gdbm functions? Available through the GDBM_File interface. periodt ✨

⚠️ real talk though: unlike Perl's built-in hashes, it is not safe to delete the current item from a GDBM_File tied hash while you're iterating over it with each. That's just a limitation of the gdbm library, not a skill issue πŸ™ˆ

πŸŽ€ Tie πŸŽ€

Use Perl's built-in tie to associate a GDBM database with a Perl hash:

tie %hash, 'GDBM_File', $filename, $flags, $mode;

Here's the breakdown, bestie:

  • $filename β€” the name of the database file you wanna open or create.
  • $flags β€” a bitwise OR of an access mode plus optional modifiers.
  • $mode β€” the file mode, we'll get to it.

Access mode is one of these four, pick exactly one:

  • GDBM_READER β€” open an existing database file in read-only mode.
  • GDBM_WRITER β€” open an existing database file in read-write mode.
  • GDBM_WRCREAT β€” if the database file exists, open it read-write. If it doesn't exist, create it first, then open read-write.
  • GDBM_NEWDB β€” create a new database and open it read-write. If the database already exists, truncate it first πŸ’€ (yes, that means what you think it means).

A number of modifiers can be OR'd onto the access mode. Most of them are rarely needed (the complete list lives at <https://www.gnu.org.ua/software/gdbm/manual/Open.html>), but one is worth mentioning out loud:

  • GDBM_NUMSYNC β€” when used together with GDBM_NEWDB, it instructs GDBM to create the database in the extended (so called numsync) format. This format is best suited for crash-tolerant implementations. Peep the CRASH TOLERANCE section below for more.

The $mode parameter is the file mode used when 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.

On success, tie returns an object of class GDBM_File. On failure, it returns undef. And omg please always check the return value β€” you wanna be sure your hash actually got associated with the database file. Check out 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 (see below).

In list context, it returns a list instead:

( MINOR, MAJOR, PATCH [, GUESS] )

The GUESS component is only present if the libgdbm version is 1.8.3 or earlier. Why? Because earlier releases of libgdbm didn't include information about their own version, so the GDBM_File module has to do certain guesswork 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. 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. 2 - approximate β€” the major and minor number are guaranteed to be correct. The patchlevel is set to the upper bound.
  3. 3 - rough guess β€” the version is guaranteed to be not newer than MAJOR.MINOR.

😭 ERROR HANDLING 😭

πŸ’… $GDBM_File::gdbm_errno πŸ’…

When referenced in numeric context, this retrieves the current value of the gdbm_errno variable, i.e. 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 though β€” that list includes all error codes defined for the most recent version of gdbm, and depending on the actual version of the library GDBM_File was built with, some of these may be missing. 🫠

In string context, $gdbm_errno returns a human-readable description of the error. If necessary, that description includes the value of $!. Which makes it chef's kiss perfect for diagnostic messages. For example, the usual tying sequence is:

tie %hash, 'GDBM_File', $filename, GDBM_WRCREAT, 0640
     or die "$GDBM_File::gdbm_errno";

The following, more complex, example shows 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";
    }
}

🌸 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.

✨ DATABASE METHODS ✨

okay so now we're getting into the actual database methods, and bestie, there are a LOT of them. but don't worry, we'll go through each one, no cap. πŸ’…


close

$db->close;

Closes the database. Normally you'd just do untie. But here's the tea: you need this function if you explicitly assigned the result of tie to a variable, and you wanna release the database to another user. Consider this code, bestie:

$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, since the database would remain referenced by $db, and as a consequence, the database file would remain locked. Calling $db->close ensures the database file is closed and unlocked. πŸ”“

so yeah, if you're holding onto that $db reference, you gotta close it yourself. periodt.

errno

$db->errno

Returns the last error status associated with this database. In string context, returns a human-readable description of the error. See also the $GDBM_File::gdbm_errno variable we talked about above. πŸ‘€

syserrno

$db->syserrno

Returns the last system error status (the C errno variable), associated with this database. 🐧

strerror

$db->strerror

Returns a textual description of the last error that occurred in this database. πŸ“

clear_error

$db->clear_error

Clear error status. 🧹

needs_recovery

$db->needs_recovery

Returns true if the database needs recovery. πŸš‘

reorganize

$db->reorganize;

Reorganizes the database. πŸ”„

sync

$db->sync;

Synchronizes recent changes to the database with its disk copy. πŸ’Ύ

count

$n = $db->count;

Returns the number of keys in the database. πŸ”’

flags

$db->flags;

Returns the flags passed as the 4th argument to tie. 🚩

dbname

$db->dbname;

Returns the database name (i.e. the 3rd argument to tie). πŸ“›

cache_size

$db->cache_size;
$db->cache_size($newsize);

Returns the size of the internal GDBM cache for that database. πŸ—„οΈ

Called with an argument, sets the size to $newsize. ✨

block_size

$db->block_size;

Returns the block size of the database. 🧱

sync_mode

$db->sync_mode;
$db->sync_mode($bool);

Returns the status of the automatic synchronization mode. Called with an 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. ⚑

Synchronization mode is off by default. 🚫

centfree

$db->centfree;
$db->centfree($bool);

Returns the status of the central free block pool (0 - disabled, 1 - enabled). 🏊

With an argument, changes its status. πŸ”§

By default, the central free block pool is disabled. 🚫

coalesce

$db->coalesce;
$db->coalesce($bool);
bestie, the manual doesn't spill any tea on what this does. just the signatures. so here they are, in all their mysterious glory. 🀫

mmap

$db->mmap;

Returns true if memory mapping is enabled. πŸ—ΊοΈ

This method will croak if the libgdbm library is compiled without memory mapping support. πŸ’€

mmapsize

$db->mmapsize;
$db->mmapsize($newsize);

If memory mapping is enabled, returns the size of memory mapping. With an argument, sets the size to $newsize. πŸ“

This method will croak if the libgdbm library is compiled without memory mapping support. πŸ’€

recover

$db->recover(%args);

Recovers data from a failed database. %args is optional and can contain the following keys: πŸ› οΈ

  • err => sub { ... } β€” Reference to code for detailed error reporting. Upon encountering an error, recover will 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, recover aborts and returns an error. πŸ”‘
  • max_failed_buckets => $n β€” Maximum allowed number of failed buckets. If the actual number becomes equal to $n, recover aborts and returns an 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

$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. πŸ“–

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. πŸ‘Œ

dump

$db->dump($filename, %options)

Creates a dump of the database file in $filename. Such a 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 to MODE. πŸ”§
  • overwrite => 1 β€” Silently overwrite existing files. πŸ—‘οΈ

load

$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 bestie, this one is genuinely iconic. Crash tolerance is a new feature that β€” if the OS and the filesystem are feeling generous and give it the right support β€” guarantees that a logically consistent recent state of the database can be recovered after a crash. Like a power outage, an OS kernel panic, or whatever other unhinged thing the universe throws at your machine. πŸ”₯

Crash tolerance support showed up in gdbm version 1.21. The theory behind it is explained 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 lore on the gdbm implementation, the GDBM Manual has you: <https://www.gnu.org.ua/software/gdbm/manual/Crash-Tolerance.html>. Everything below is about the Perl interface specifically, iykyk. πŸ’…

For maximum robustness, we recommend using the extended database format for crash tolerant databases. To create a database in extended format, open it with GDBM_NEWDB|GDBM_NUMSYNC, like this:

$db = tie %hash, 'GDBM_File', $filename,
          GDBM_NEWDB|GDBM_NUMSYNC, 0640;

And to convert an existing database over to the extended format, use the convert method described above, like:

$db->convert(GDBM_NUMSYNC);

✨ crash_tolerance_status ✨

GDBM_File->crash_tolerance_status;

This static method returns the status of crash tolerance support. A non-zero value means crash tolerance is compiled in and supported by the operating system. Slay. 🫢

✨ failure_atomic ✨

$db->failure_atomic($even, $odd)

This enables crash tolerance for the database $db. The arguments are the pathnames of two files that will be created and filled with snapshots of the database file. Heads up bestie: those two files must not exist when this method is called, and they must live on the same filesystem as the database file. That filesystem also has to support the reflink operation (<https://www.gnu.org.ua/software/gdbm/manual/Filesystems-supporting-crash-tolerance.html>). No reflink, no deal. 😭

After a successful call to failure_atomic, every call to the $db-sync> method will make an efficient reflink snapshot of the database file in one of these files; consecutive calls to sync alternate between the two β€” hence the names $even and $odd. Cute, right? πŸŽ€

The most recent of these files can be used 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);

Give it the two snapshot names (the ones you used earlier in a call to failure_atomic), and this method picks the one suitable for database recovery β€” aka the file holding the most recent database snapshot. πŸ’–

In scalar context, it returns the selected file name, or undef if it failed.

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 is undef, and the status is one of these:

  • GDBM_SNAPSHOT_BAD β€” Neither snapshot file is applicable. This means the crash happened before a call to failure_atomic completed. In this case, the best move is to fall back on a safe backup copy of the data file. πŸ™ˆ
  • GDBM_SNAPSHOT_ERR β€” A system error occurred. Go examine $! for the details. There's a comprehensive list of error codes and their meanings at <https://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 only happen for databases in standard format.
  • GDBM_SNAPSHOT_SUSPICIOUS β€” The numsync counters of the two snapshots differ by more than one. The most probable reason is programmer's error: the two parameters refer to snapshots belonging to different database files. Oops. πŸ’€

πŸ“¦ 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 instead. You can grab 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 want to transfer a GDBM file over the wire, dump it to a portable format first, bestie. Don't just raw-dog it across systems. βœ‹
Do not accept GDBM files from untrusted sources. Seriously. 🚫

Robustness of GDBM against corrupted databases depends highly on its version. Versions prior to 1.15 did not implement any validity checking, so a corrupted or maliciously crafted database file could cause perl to crash or even expose a security vulnerability. Versions between 1.15 and 1.20 were progressively strengthened against invalid inputs. And finally, version 1.21 had undergone extensive fuzzy checking which proved its ability to withstand any kinds of inputs without crashing. Glow up of the century honestly. πŸ‘‘

πŸ‘€ SEE ALSO πŸ‘€

perl(1), DB_File(3), perldbmfilter, gdbm(3), <https://www.gnu.org.ua/software/gdbm/manual.html>.


And that's a wrap on this whole page, babe! 🌈 Written up against perl v5.42.3, dated 2026-08-03, and yeah β€” it's the GDBM_File(3pm) page. Go forth and tie your hashes to databases responsibly. Periodt. πŸ’œπŸŒΈβœ¨

πŸ“¦ where this page comes from