O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Treating a Text File as a Database Array

Problem

You’d like to treat a text file as an array of lines with read-write privileges. You might want to do that so you could easily update the Nth line.

Solution

The DB_File module lets you tie a text file to an array.

use DB_File;

tie(@array, "DB_File", "/tmp/textfile", O_RDWR|O_CREAT, 0666, $DB_RECNO)
    or die "Cannot open file 'text': $!\en" ;

$array[4] = "a new line";
untie @array;

Description

Updating a textfile in place is surprisingly tricky, as noted in Chapter 7. The RECNO binding provides a nice way to address the file as though it were a simple array of lines— the way everyone always seems to think they can.

Working with files this way can be odd. For one thing, the zeroth element of the tied array is the first line of the file. More importantly, tied arrays aren’t as fully featured as tied hashes are. This will be fixed in a future version of Perl— patches are already available, in fact.

As you can see from the example above, the tied array interface is limited. To make the interface more useful, methods supplied with DB_File simulate the standard array operations that are not currently implemented in Perl’s tied array interface. Save the return value from tie function or retrieve it later from the tied hash using the tied function. Use this object to access the following methods:

$X->push(LIST)

Pushes elements of LIST to the end of the array.

$value = $X->pop

Removes and returns the last element of the array.

$X->shift

Removes and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required