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