The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Tie::File - Access the lines of a disk file via a Perl array

SYNOPSIS

        # This file documents Tie::File version 0.18

        tie @array, 'Tie::File', filename or die ...;

        $array[13] = 'blah';     # line 13 of the file is now 'blah'
        print $array[42];        # display line 42 of the file

        $n_recs = @array;        # how many records are in the file?
        $#array = $n_recs - 2;   # chop records off the end

        # As you would expect:

        push @array, new recs...;
        my $r1 = pop @array;
        unshift @array, new recs...;
        my $r1 = shift @array;
        @old_recs = splice @array, 3, 7, new recs...;

        untie @array;            # all finished

        # See below for more options and methods

DESCRIPTION

Tie::File represents a regular text file as a Perl array. 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.

The file is not loaded into memory, so this will work even for gigantic files.

Changes to the array are reflected in the file immediately.

recsep

What is a 'record'? By default, the meaning is the same as for the <...> operator: It's a string terminated by $/, which is probably "\n". You may change the definition of "record" by supplying the recsep option in the tie call:

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

This says that records are delimited by the string es. If the file contained the following data:

        Curse these pesky flies!\n

then the @array would appear to have four elements:

        "Curse thes"
        "e pes"
        "ky flies"
        "!\n"

Windows users will probably want to use recsep => "\r\n" to get files terminated with the usual CRLF sequence.

An undefined value is not permitted as a record separator. Perl's special "paragraph mode" semantics (à la $/ = "") are not emulated.

Records read from the tied array will have the record separator string on the end, just as if they were read from the <...> operator. Records stored into the array will have the record separator string appended before they are written to the file, if they don't have one already. For example, if the record separator string is "\n", then the following two lines do exactly the same thing:

        $array[17] = "Cherry pie";
        $array[17] = "Cherry pie\n";

The result is that the contents of line 17 of the file will be replaced with "Cherry pie"; a newline character will separate line 17 from line 18. This means that in particular, this will do nothing:

        chomp $array[17];

Because the chomped value will have the separator reattached when it is written back to the file. There is no way to create a file whose trailing record separator string is missing.

Inserting records that contain the record separator string will produce a reasonable result, but if you can't foresee what this result will be, you'd better avoid doing this.

mode

Normally, the specified file will be opened for read and write access, and will be created if it does not exist. (That is, the flags O_RDWR | O_CREAT are supplied in the open call.) If you want to change this, you may supply alternative flags in the mode option. See Fcntl for a listing of available flags. For example:

        # open the file if it exists, but fail if it does not exist
        use Fcntl 'O_RDWR';
        tie @array, 'Tie::File', $file, mode => O_RDWR;

        # create the file if it does not exist
        use Fcntl 'O_RDWR', 'O_CREAT';
        tie @array, 'Tie::File', $file, mode => O_RDWR | O_CREAT;

        # open an existing file in read-only mode
        use Fcntl 'O_RDONLY';
        tie @array, 'Tie::File', $file, mode => O_RDONLY;

Opening the data file in write-only or append mode is not supported.

cachesize

Records read in from the file are cached, to avoid having to re-read them repeatedly. If you read the same record twice, the first time it will be stored in memory, and the second time it will be fetched from memory.

The cache has a bounded size; when it exceeds this size, the least-recently visited records will be purged from the cache. The default size is 2Mib. You can adjust the amount of space used for the cache by supplying the cachesize option. The argument is the desired cache size, in bytes.

        # I have a lot of memory, so use a large cache to speed up access
        tie @array, 'Tie::File', $file, cachesize => 20_000_000;

Setting the cache size to 0 will inhibit caching; records will be fetched from disk every time you examine them.

Option Format

-mode is a synonym for mode. -recsep is a synonym for recsep. -cachesize is a synonym for cachesize. You get the idea.

Public Methods

The tie call returns an object, say $o. You may call

        $rec = $o->FETCH($n);
        $o->STORE($n, $rec);

to fetch or store the record at line $n, respectively. The only other public method in this package is:

flock

        $o->flock(MODE)

will lock the tied file. MODE has the same meaning as the second argument to the Perl built-in flock function; for example LOCK_SH or LOCK_EX | LOCK_NB. (These constants are provided by the use Fcntl ':flock' declaration.)

MODE is optional; $o->flock simply locks the file with LOCK_EX.

The best way to unlock a file is to discard the object and untie the array. It is probably unsafe to unlock the file without also untying it, because if you do, changes may remain unwritten inside the object. That is why there is no shortcut for unlocking. If you really want to unlock the file prematurely, you know what to do; if you don't know what to do, then don't do it.

All the usual warnings about file locking apply here. In particular, note that file locking in Perl is advisory, which means that holding a lock will not prevent anyone else from reading, writing, or erasing the file; it only prevents them from getting another lock at the same time. Locks are analogous to green traffic lights: If you have a green light, that does not prevent the idiot coming the other way from plowing into you sideways; it merely guarantees to you that the idiot does not also have a green light at the same time.

Tying to an already-opened filehandle

If $fh is a filehandle, such as is returned by IO::File or one of the other IO modules, you may use:

        tie @array, 'Tie::File', $fh, ...;

Similarly if you opened that handle FH with regular open or sysopen, you may use:

        tie @array, 'Tie::File', \*FH, ...;

Handles that were opened write-only won't work. Handles that were opened read-only will work as long as you don't try to write to them. Handles must be attached to seekable sources of data---that means no pipes or sockets. If you try to supply a non-seekable handle, the tie call will try to abort your program. This feature is not yet supported under VMS.

CAVEATS

(That's Latin for 'warnings'.)

Efficiency Note

Every effort was made to make this module efficient. Nevertheless, changing the size of a record in the middle of a large file will always be slow, because everything after the new record must be moved.

In particular, note that:

        # million-line file
        for (@file_array) {
          $_ .= 'x';
        }

is likely to be very slow, because the first iteration must relocate lines 1 through 999,999; the second iteration must relocate lines 2 through 999,999, and so on. The relocation is done using block writes, however, so it's not as slow as it might be.

A soon-to-be-released version of this module will provide a mechanism for getting better performance in such cases, by deferring the writing until it can be done all at once.

Efficiency Note 2

Not every effort was made to make this module as efficient as possible. FETCHSIZE should use binary search instead of linear search. The cache's LRU queue should be a heap instead of a list. These defects are probably minor; in any event, they will be fixed in a later version of the module.

Efficiency Note 3

The author has supposed that since this module is concerned with file I/O, almost all normal use of it will be heavily I/O bound, and that the time to maintain complicated data structures inside the module will be dominated by the time to actually perform the I/O. This suggests, for example, that an LRU read-cache is a good tradeoff, even if it requires substantial adjustment following a splice operation.

CAVEATS

(That's Latin for 'warnings'.)

The behavior of tied arrays is not precisely the same as for regular arrays. For example:

        undef $a[10];  print "How unusual!\n" if $a[10];

undef-ing a Tie::File array element just blanks out the corresponding record in the file. When you read it back again, you'll see the record separator (typically, $a[10] will appear to contain "\n") so the supposedly-undef'ed value will be true.

There are other minor differences, but in general, the correspondence is extremely close.

AUTHOR

Mark Jason Dominus

To contact the author, send email to: mjd-perl-tiefile+@plover.com

To receive an announcement whenever a new version of this module is released, send a blank email message to mjd-perl-tiefile-subscribe@plover.com.

LICENSE

Tie::File version 0.18 is copyright (C) 2002 Mark Jason Dominus.

This library is free software; you may redistribute it and/or modify it under the same terms as Perl itself.

These terms include your choice of (1) the Perl Artistic Licence, or (2) version 2 of the GNU General Public License as published by the Free Software Foundation, or (3) any later version of the GNU General Public License.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this library program; it should be in the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA

For licensing inquiries, contact the author at:

        Mark Jason Dominus
        255 S. Warnock St.
        Philadelphia, PA 19107

WARRANTY

Tie::File version 0.18 comes with ABSOLUTELY NO WARRANTY. For details, see the license.

THANKS

Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the core when I hadn't written it yet, and for generally being helpful, supportive, and competent. (Usually the rule is "choose any one.") Also big thanks to Abhijit Menon-Sen for all of the same things.

Special thanks to Craig Berry (for VMS portability help), Randy Kobes (for Win32 portability help), the rest of the CPAN testers (for testing).

More thanks to: Gerrit Haase / Nick Ing-Simmons / Tassilo von Parseval / H. Dieter Pearcey / Peter Somu / Tels

TODO

Test DELETE machinery more carefully.

More tests. (Configuration options, cache flushery. _twrite should be tested separately, because there are a lot of weird special cases lurking in there.)

More tests. (Stuff I didn't think of yet.)

Deferred writing. (!!!)

Paragraph mode?

More tests.

Fixed-length mode.

Maybe an autolocking mode?