home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeJava and XSLTSearch this book

8.216. 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 are equivalent:

$lines[5] = "Sixty6";
$lines[5] = "Sixty6\n";
autochomp
If specified, and if \n is your default recsep, \n will be removed as the record separator. Default is 0.

mode
Sets if the file will be set for read, write, or read/write access. Options include O_RDWR and O_CREAT:

use Fcntl 'O_RDWR', 'O_CREAT';
 
# Open file RDWR, or CREAT if $file doesn't exist
tie @lines, 'Tie::File', $file, mode => O_RDWR | O_CREAT;
memory
Sets the upper limit on the amount of memory that Tie::File will consume.

dw_size
Specifies that data should be written into a deferred write buffer of a given size instead of in the file itself.

See the documentation for Tie for a description of the additional tie() methods.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.