Record-Oriented Approach
In
this section, we will study three modules that essentially depend on
the DBM library. DBM is a disk-based hash table library, originally
written by Ken Thompson for the Seventh Edition Unix
system. This library has since spawned many variants: SDBM (Simple
DBM, a public-domain module bundled with Perl), NDBM (New DBM, which
is packaged with some operating systems), and GDBM (from the Free
Software Foundation). All these libraries can be accessed from
equivalent Perl modules, which use Perl’s
tie
facility to provide transparent access to the
disk-based table. Performance and portability are the only criteria
for selecting one of these systems. Be warned that the files produced
by these approaches are not interchangeable.
DBM
We use SDBM here, because it is bundled with Perl. The SDBM_File module provides a wrapper over this extension:
use Fcntl; use SDBM_File; tie (%capital, 'SDBM_File', 'capitals.dat', O_RDWR|O_CREAT, 0666) || die $!; $capital{USA} = "Washington D.C."; $capital{Colombia} = "Bogota"; untie %capital;
The tie
statement associates the in-memory hash
variable, %capital
, with the disk-based hash file,
capitals.dat
. Read and write accesses to
%capital
are automatically translated to
corresponding accesses to the file. untie
breaks
this association and flushes any pending changes to the disk.
O_RDWR
and O_CREAT
,
“constants” imported from Fcntl
,
specify that capitals.dat
is to be opened for reading and writing, and to create it if it doesn’t exist. ...
Get Advanced Perl Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.