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:
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";
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;
See the documentation for Tie for a description of the additional tie() methods.
Copyright © 2002 O'Reilly & Associates. All rights reserved.