Tie::File

Represents a regular text file as a Perl array, such that each element in the array corresponds to a record in the file. The first line of the file is element 0 of the array, the second line is element 1, and so on. When you add a new item to the array, this change will be noted in the file immediately. Note that the file isn’t loaded into memory, so the files can be very large if needed. Tie::File is shipped with the Perl 5.8 source kit.

Let’s say that we have a file that contains:

One
Two
Three
Four
Five
Six

You can use Tie::File to report about the contents of the file as follows:

#!/usr/local/bin/perl -w

use Tile::File;

my $infile = 'mynotes.db.txt';
my @lines;
 
tie(@lines, 'Tie::File', $infile)
die("can't open $infile: $!");

my $n_recs = @lines;
print "$infile has [$n_recs]\n";

Now, set the second line of the file to 3:

$lines[2] = 3;

and lowercase everything that’s in the file:

foreach my $line (@lines) {
    lc($line);
}

Add one line to the file:

push(@lines, "Here's one more for you");

Now we’re done:

untie @lines;

Tie::File supports the following options:

recsep

Changes $/ to what you’ll use to separate the records (or lines) in your file. recsep may not be undefined.

my $file = 'datafile';
my $recsep = "\cA"; # Break records on ^A

tie @lines, 'Tie::File', $file, recsep => $recsep;

Given the line:

this^Athat^Athe^Aother^Athing\n

Tie::File would see the records like so:

0: this
1: that
2: the
3: other
4: thing

If you do not specify a recsep, Tie::File will default to \n. Thus, the following ...

Get Perl in a Nutshell, 2nd Edition 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.