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 ...
Get Perl Cookbook 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.