Fixed-Length Random-Access Databases

Another form of persistent data is the fixed-length, record-oriented disk file. In this scheme, the data consists of a number of records of identical length. The numbering of the records is either not important or determined by some indexing scheme.

For example, we might have a series of records in which the data has 40 characters of first name, a one-character middle initial, 40 characters of last name, and then a two-byte integer for the age. Each record is then 83 bytes long. If we were reading all of the data in the database, we’d read chunks of 83 bytes until we got to the end. If we wanted to go to the fifth record, we’d skip ahead four times 83 bytes (332 bytes) and read the fifth record directly.

Perl supports programs that use such a disk file. A few things are necessary in addition to what you already know:

  • Opening a disk file for both reading and writing, and setting the filehandle to binary mode

  • Moving around in this file to an arbitrary position

  • Fetching data by a length rather than up to the next newline

  • Writing data down in fixed-length blocks

The open function takes an additional plus sign before its I/O direction specification to indicate that the file is really being opened for both reading and writing. For example:

open(A,"+<b");  # open file b read/write (error if file absent)
open(C,"+>d");  # create file d, with read/write access
open(E,"+>>f"); # open or create file f with read/write access

Notice that all we’ve done was to prepend ...

Get Learning Perl on Win32 Systems 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.