1[![](https://github.com/toddr/Tie-File/workflows/linux/badge.svg)](https://github.com/toddr/Tie-File/actions) [![](https://github.com/toddr/Tie-File/workflows/macos/badge.svg)](https://github.com/toddr/Tie-File/actions) [![](https://github.com/toddr/Tie-File/workflows/windows/badge.svg)](https://github.com/toddr/Tie-File/actions)
2
3# NAME
4
5Tie::File - Access the lines of a disk file via a Perl array
6
7# SYNOPSIS
8
9        # This file documents Tie::File version 0.98
10        use Tie::File;
11
12        tie @array, 'Tie::File', filename or die ...;
13
14        $array[13] = 'blah';     # line 13 of the file is now 'blah'
15        print $array[42];        # display line 42 of the file
16
17        $n_recs = @array;        # how many records are in the file?
18        $#array -= 2;            # chop two records off the end
19
20
21        for (@array) {
22          s/PERL/Perl/g;         # Replace PERL with Perl everywhere in the file
23        }
24
25        # These are just like regular push, pop, unshift, shift, and splice
26        # Except that they modify the file in the way you would expect
27
28        push @array, new recs...;
29        my $r1 = pop @array;
30        unshift @array, new recs...;
31        my $r2 = shift @array;
32        @old_recs = splice @array, 3, 7, new recs...;
33
34        untie @array;            # all finished
35
36# DESCRIPTION
37
38`Tie::File` represents a regular text file as a Perl array.  Each
39element in the array corresponds to a record in the file.  The first
40line of the file is element 0 of the array; the second line is element
411, and so on.
42
43The file is _not_ loaded into memory, so this will work even for
44gigantic files.
45
46Changes to the array are reflected in the file immediately.
47
48Lazy people and beginners may now stop reading the manual.
49
50## `recsep`
51
52What is a 'record'?  By default, the meaning is the same as for the
53`<...>` operator: It's a string terminated by `$/`, which is
54probably `"\n"`.  (Minor exception: on DOS and Win32 systems, a
55'record' is a string terminated by `"\r\n"`.)  You may change the
56definition of "record" by supplying the `recsep` option in the `tie`
57call:
58
59        tie @array, 'Tie::File', $file, recsep => 'es';
60
61This says that records are delimited by the string `es`.  If the file
62contained the following data:
63
64        Curse these pesky flies!\n
65
66then the `@array` would appear to have four elements:
67
68        "Curse th"
69        "e p"
70        "ky fli"
71        "!\n"
72
73An undefined value is not permitted as a record separator.  Perl's
74special "paragraph mode" semantics (à la `$/ = ""`) are not
75emulated.
76
77Records read from the tied array do not have the record separator
78string on the end; this is to allow
79
80        $array[17] .= "extra";
81
82to work as expected.
83
84(See ["autochomp"](#autochomp), below.)  Records stored into the array will have
85the record separator string appended before they are written to the
86file, if they don't have one already.  For example, if the record
87separator string is `"\n"`, then the following two lines do exactly
88the same thing:
89
90        $array[17] = "Cherry pie";
91        $array[17] = "Cherry pie\n";
92
93The result is that the contents of line 17 of the file will be
94replaced with "Cherry pie"; a newline character will separate line 17
95from line 18.  This means that this code will do nothing:
96
97        chomp $array[17];
98
99Because the `chomp`ed value will have the separator reattached when
100it is written back to the file.  There is no way to create a file
101whose trailing record separator string is missing.
102
103Inserting records that _contain_ the record separator string is not
104supported by this module.  It will probably produce a reasonable
105result, but what this result will be may change in a future version.
106Use 'splice' to insert records or to replace one record with several.
107
108## `autochomp`
109
110Normally, array elements have the record separator removed, so that if
111the file contains the text
112
113        Gold
114        Frankincense
115        Myrrh
116
117the tied array will appear to contain `("Gold", "Frankincense",
118"Myrrh")`.  If you set `autochomp` to a false value, the record
119separator will not be removed.  If the file above was tied with
120
121        tie @gifts, "Tie::File", $gifts, autochomp => 0;
122
123then the array `@gifts` would appear to contain `("Gold\n",
124"Frankincense\n", "Myrrh\n")`, or (on Win32 systems) `("Gold\r\n",
125"Frankincense\r\n", "Myrrh\r\n")`.
126
127## `mode`
128
129Normally, the specified file will be opened for read and write access,
130and will be created if it does not exist.  (That is, the flags
131`O_RDWR | O_CREAT` are supplied in the `open` call.)  If you want to
132change this, you may supply alternative flags in the `mode` option.
133See [Fcntl](https://metacpan.org/pod/Fcntl) for a listing of available flags.
134For example:
135
136        # open the file if it exists, but fail if it does not exist
137        use Fcntl 'O_RDWR';
138        tie @array, 'Tie::File', $file, mode => O_RDWR;
139
140        # create the file if it does not exist
141        use Fcntl 'O_RDWR', 'O_CREAT';
142        tie @array, 'Tie::File', $file, mode => O_RDWR | O_CREAT;
143
144        # open an existing file in read-only mode
145        use Fcntl 'O_RDONLY';
146        tie @array, 'Tie::File', $file, mode => O_RDONLY;
147
148Opening the data file in write-only or append mode is not supported.
149
150## `memory`
151
152This is an upper limit on the amount of memory that `Tie::File` will
153consume at any time while managing the file.  This is used for two
154things: managing the _read cache_ and managing the _deferred write
155buffer_.
156
157Records read in from the file are cached, to avoid having to re-read
158them repeatedly.  If you read the same record twice, the first time it
159will be stored in memory, and the second time it will be fetched from
160the _read cache_.  The amount of data in the read cache will not
161exceed the value you specified for `memory`.  If `Tie::File` wants
162to cache a new record, but the read cache is full, it will make room
163by expiring the least-recently visited records from the read cache.
164
165The default memory limit is 2Mib.  You can adjust the maximum read
166cache size by supplying the `memory` option.  The argument is the
167desired cache size, in bytes.
168
169        # I have a lot of memory, so use a large cache to speed up access
170        tie @array, 'Tie::File', $file, memory => 20_000_000;
171
172Setting the memory limit to 0 will inhibit caching; records will be
173fetched from disk every time you examine them.
174
175The `memory` value is not an absolute or exact limit on the memory
176used.  `Tie::File` objects contains some structures besides the read
177cache and the deferred write buffer, whose sizes are not charged
178against `memory`.
179
180The cache itself consumes about 310 bytes per cached record, so if
181your file has many short records, you may want to decrease the cache
182memory limit, or else the cache overhead may exceed the size of the
183cached data.
184
185## `dw_size`
186
187(This is an advanced feature.  Skip this section on first reading.)
188
189If you use deferred writing (See ["Deferred Writing"](#deferred-writing), below) then
190data you write into the array will not be written directly to the
191file; instead, it will be saved in the _deferred write buffer_ to be
192written out later.  Data in the deferred write buffer is also charged
193against the memory limit you set with the `memory` option.
194
195You may set the `dw_size` option to limit the amount of data that can
196be saved in the deferred write buffer.  This limit may not exceed the
197total memory limit.  For example, if you set `dw_size` to 1000 and
198`memory` to 2500, that means that no more than 1000 bytes of deferred
199writes will be saved up.  The space available for the read cache will
200vary, but it will always be at least 1500 bytes (if the deferred write
201buffer is full) and it could grow as large as 2500 bytes (if the
202deferred write buffer is empty.)
203
204If you don't specify a `dw_size`, it defaults to the entire memory
205limit.
206
207## Option Format
208
209`-mode` is a synonym for `mode`.  `-recsep` is a synonym for
210`recsep`.  `-memory` is a synonym for `memory`.  You get the
211idea.
212
213# Public Methods
214
215The `tie` call returns an object, say `$o`.  You may call
216
217        $rec = $o->FETCH($n);
218        $o->STORE($n, $rec);
219
220to fetch or store the record at line `$n`, respectively; similarly
221the other tied array methods.  (See [perltie](https://metacpan.org/pod/perltie) for details.)  You may
222also call the following methods on this object:
223
224## `flock`
225
226        $o->flock(MODE)
227
228will lock the tied file.  `MODE` has the same meaning as the second
229argument to the Perl built-in `flock` function; for example
230`LOCK_SH` or `LOCK_EX | LOCK_NB`.  (These constants are provided by
231the `use Fcntl ':flock'` declaration.)
232
233`MODE` is optional; the default is `LOCK_EX`.
234
235`Tie::File` maintains an internal table of the byte offset of each
236record it has seen in the file.
237
238When you use `flock` to lock the file, `Tie::File` assumes that the
239read cache is no longer trustworthy, because another process might
240have modified the file since the last time it was read.  Therefore, a
241successful call to `flock` discards the contents of the read cache
242and the internal record offset table.
243
244`Tie::File` promises that the following sequence of operations will
245be safe:
246
247        my $o = tie @array, "Tie::File", $filename;
248        $o->flock;
249
250In particular, `Tie::File` will _not_ read or write the file during
251the `tie` call.  (Exception: Using `mode => O_TRUNC` will, of
252course, erase the file during the `tie` call.  If you want to do this
253safely, then open the file without `O_TRUNC`, lock the file, and use
254`@array = ()`.)
255
256The best way to unlock a file is to discard the object and untie the
257array.  It is probably unsafe to unlock the file without also untying
258it, because if you do, changes may remain unwritten inside the object.
259That is why there is no shortcut for unlocking.  If you really want to
260unlock the file prematurely, you know what to do; if you don't know
261what to do, then don't do it.
262
263All the usual warnings about file locking apply here.  In particular,
264note that file locking in Perl is **advisory**, which means that
265holding a lock will not prevent anyone else from reading, writing, or
266erasing the file; it only prevents them from getting another lock at
267the same time.  Locks are analogous to green traffic lights: If you
268have a green light, that does not prevent the idiot coming the other
269way from plowing into you sideways; it merely guarantees to you that
270the idiot does not also have a green light at the same time.
271
272## `autochomp`
273
274        my $old_value = $o->autochomp(0);    # disable autochomp option
275        my $old_value = $o->autochomp(1);    #  enable autochomp option
276
277        my $ac = $o->autochomp();   # recover current value
278
279See ["autochomp"](#autochomp), above.
280
281## `defer`, `flush`, `discard`, and `autodefer`
282
283See ["Deferred Writing"](#deferred-writing), below.
284
285## `offset`
286
287        $off = $o->offset($n);
288
289This method returns the byte offset of the start of the `$n`th record
290in the file.  If there is no such record, it returns an undefined
291value.
292
293# Tying to an already-opened filehandle
294
295If `$fh` is a filehandle, such as is returned by `IO::File` or one
296of the other `IO` modules, you may use:
297
298        tie @array, 'Tie::File', $fh, ...;
299
300Similarly if you opened that handle `FH` with regular `open` or
301`sysopen`, you may use:
302
303        tie @array, 'Tie::File', \*FH, ...;
304
305Handles that were opened write-only won't work.  Handles that were
306opened read-only will work as long as you don't try to modify the
307array.  Handles must be attached to seekable sources of data---that
308means no pipes or sockets.  If `Tie::File` can detect that you
309supplied a non-seekable handle, the `tie` call will throw an
310exception.  (On Unix systems, it can detect this.)
311
312Note that Tie::File will only close any filehandles that it opened
313internally.  If you passed it a filehandle as above, you "own" the
314filehandle, and are responsible for closing it after you have untied
315the @array.
316
317# Deferred Writing
318
319(This is an advanced feature.  Skip this section on first reading.)
320
321Normally, modifying a `Tie::File` array writes to the underlying file
322immediately.  Every assignment like `$a[3] = ...` rewrites as much of
323the file as is necessary; typically, everything from line 3 through
324the end will need to be rewritten.  This is the simplest and most
325transparent behavior.  Performance even for large files is reasonably
326good.
327
328However, under some circumstances, this behavior may be excessively
329slow.  For example, suppose you have a million-record file, and you
330want to do:
331
332        for (@FILE) {
333          $_ = "> $_";
334        }
335
336The first time through the loop, you will rewrite the entire file,
337from line 0 through the end.  The second time through the loop, you
338will rewrite the entire file from line 1 through the end.  The third
339time through the loop, you will rewrite the entire file from line 2 to
340the end.  And so on.
341
342If the performance in such cases is unacceptable, you may defer the
343actual writing, and then have it done all at once.  The following loop
344will perform much better for large files:
345
346        (tied @a)->defer;
347        for (@a) {
348          $_ = "> $_";
349        }
350        (tied @a)->flush;
351
352If `Tie::File`'s memory limit is large enough, all the writing will
353done in memory.  Then, when you call `->flush`, the entire file
354will be rewritten in a single pass.
355
356(Actually, the preceding discussion is something of a fib.  You don't
357need to enable deferred writing to get good performance for this
358common case, because `Tie::File` will do it for you automatically
359unless you specifically tell it not to.  See ["Autodeferring"](#autodeferring),
360below.)
361
362Calling `->flush` returns the array to immediate-write mode.  If
363you wish to discard the deferred writes, you may call `->discard`
364instead of `->flush`.  Note that in some cases, some of the data
365will have been written already, and it will be too late for
366`->discard` to discard all the changes.  Support for
367`->discard` may be withdrawn in a future version of `Tie::File`.
368
369Deferred writes are cached in memory up to the limit specified by the
370`dw_size` option (see above).  If the deferred-write buffer is full
371and you try to write still more deferred data, the buffer will be
372flushed.  All buffered data will be written immediately, the buffer
373will be emptied, and the now-empty space will be used for future
374deferred writes.
375
376If the deferred-write buffer isn't yet full, but the total size of the
377buffer and the read cache would exceed the `memory` limit, the oldest
378records will be expired from the read cache until the total size is
379under the limit.
380
381`push`, `pop`, `shift`, `unshift`, and `splice` cannot be
382deferred.  When you perform one of these operations, any deferred data
383is written to the file and the operation is performed immediately.
384This may change in a future version.
385
386If you resize the array with deferred writing enabled, the file will
387be resized immediately, but deferred records will not be written.
388This has a surprising consequence: `@a = (...)` erases the file
389immediately, but the writing of the actual data is deferred.  This
390might be a bug.  If it is a bug, it will be fixed in a future version.
391
392## Autodeferring
393
394`Tie::File` tries to guess when deferred writing might be helpful,
395and to turn it on and off automatically.
396
397        for (@a) {
398          $_ = "> $_";
399        }
400
401In this example, only the first two assignments will be done
402immediately; after this, all the changes to the file will be deferred
403up to the user-specified memory limit.
404
405You should usually be able to ignore this and just use the module
406without thinking about deferring.  However, special applications may
407require fine control over which writes are deferred, or may require
408that all writes be immediate.  To disable the autodeferment feature,
409use
410
411        (tied @o)->autodefer(0);
412
413or
414
415        tie @array, 'Tie::File', $file, autodefer => 0;
416
417Similarly, `->autodefer(1)` re-enables autodeferment, and
418`->autodefer()` recovers the current value of the autodefer setting.
419
420# CONCURRENT ACCESS TO FILES
421
422Caching and deferred writing are inappropriate if you want the same
423file to be accessed simultaneously from more than one process.  Other
424optimizations performed internally by this module are also
425incompatible with concurrent access.  A future version of this module will
426support a `concurrent => 1` option that enables safe concurrent access.
427
428Previous versions of this documentation suggested using `memory
429&#x3d;> 0` for safe concurrent access.  This was mistaken.  Tie::File
430will not support safe concurrent access before version 0.96.
431
432# CAVEATS
433
434(That's Latin for 'warnings'.)
435
436- Reasonable effort was made to make this module efficient.  Nevertheless,
437changing the size of a record in the middle of a large file will
438always be fairly slow, because everything after the new record must be
439moved.
440- The behavior of tied arrays is not precisely the same as for regular
441arrays.  For example:
442
443            # This DOES print "How unusual!"
444            undef $a[10];  print "How unusual!\n" if defined $a[10];
445
446    `undef`-ing a `Tie::File` array element just blanks out the
447    corresponding record in the file.  When you read it back again, you'll
448    get the empty string, so the supposedly-`undef`'ed value will be
449    defined.  Similarly, if you have `autochomp` disabled, then
450
451            # This DOES print "How unusual!" if 'autochomp' is disabled
452            undef $a[10];
453            print "How unusual!\n" if $a[10];
454
455    Because when `autochomp` is disabled, `$a[10]` will read back as
456    `"\n"` (or whatever the record separator string is.)
457
458    There are other minor differences, particularly regarding `exists`
459    and `delete`, but in general, the correspondence is extremely close.
460
461- I have supposed that since this module is concerned with file I/O,
462almost all normal use of it will be heavily I/O bound.  This means
463that the time to maintain complicated data structures inside the
464module will be dominated by the time to actually perform the I/O.
465When there was an opportunity to spend CPU time to avoid doing I/O, I
466usually tried to take it.
467- You might be tempted to think that deferred writing is like
468transactions, with `flush` as `commit` and `discard` as
469`rollback`, but it isn't, so don't.
470- There is a large memory overhead for each record offset and for each
471cache entry: about 310 bytes per cached data record, and about 21 bytes per offset table entry.
472
473    The per-record overhead will limit the maximum number of records you
474    can access per file. Note that _accessing_ the length of the array
475    via `$x = scalar @tied_file` accesses **all** records and stores their
476    offsets.  The same for `foreach (@tied_file)`, even if you exit the
477    loop early.
478
479# SUBCLASSING
480
481This version promises absolutely nothing about the internals, which
482may change without notice.  A future version of the module will have a
483well-defined and stable subclassing API.
484
485# WHAT ABOUT `DB_File`?
486
487People sometimes point out that [DB\_File](https://metacpan.org/pod/DB_File) will do something similar,
488and ask why `Tie::File` module is necessary.
489
490There are a number of reasons that you might prefer `Tie::File`.
491A list is available at `http://perl.plover.com/TieFile/why-not-DB_File`.
492
493# AUTHOR
494
495Mark Jason Dominus
496
497To contact the author, send email to: `mjd-perl-tiefile+@plover.com`
498
499To receive an announcement whenever a new version of this module is
500released, send a blank email message to
501`mjd-perl-tiefile-subscribe@plover.com`.
502
503The most recent version of this module, including documentation and
504any news of importance, will be available at
505
506        http://perl.plover.com/TieFile/
507
508# LICENSE
509
510`Tie::File` version 0.96 is copyright (C) 2003 Mark Jason Dominus.
511
512This library is free software; you may redistribute it and/or modify
513it under the same terms as Perl itself.
514
515These terms are your choice of any of (1) the Perl Artistic Licence,
516or (2) version 2 of the GNU General Public License as published by the
517Free Software Foundation, or (3) any later version of the GNU General
518Public License.
519
520This library is distributed in the hope that it will be useful,
521but WITHOUT ANY WARRANTY; without even the implied warranty of
522MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
523GNU General Public License for more details.
524
525You should have received a copy of the GNU General Public License
526along with this library program; it should be in the file `COPYING`.
527If not, write to the Free Software Foundation, Inc., 51 Franklin Street,
528Fifth Floor, Boston, MA  02110-1301, USA
529
530For licensing inquiries, contact the author at:
531
532        Mark Jason Dominus
533        255 S. Warnock St.
534        Philadelphia, PA 19107
535
536# WARRANTY
537
538`Tie::File` version 0.98 comes with ABSOLUTELY NO WARRANTY.
539For details, see the license.
540
541# THANKS
542
543Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the
544core when I hadn't written it yet, and for generally being helpful,
545supportive, and competent.  (Usually the rule is "choose any one.")
546Also big thanks to Abhijit Menon-Sen for all of the same things.
547
548Special thanks to Craig Berry and Peter Prymmer (for VMS portability
549help), Randy Kobes (for Win32 portability help), Clinton Pierce and
550Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond
551the call of duty), Michael G Schwern (for testing advice), and the
552rest of the CPAN testers (for testing generally).
553
554Special thanks to Tels for suggesting several speed and memory
555optimizations.
556
557Additional thanks to:
558Edward Avis /
559Mattia Barbon /
560Tom Christiansen /
561Gerrit Haase /
562Gurusamy Sarathy /
563Jarkko Hietaniemi (again) /
564Nikola Knezevic /
565John Kominetz /
566Nick Ing-Simmons /
567Tassilo von Parseval /
568H. Dieter Pearcey /
569Slaven Rezic /
570Eric Roode /
571Peter Scott /
572Peter Somu /
573Autrijus Tang (again) /
574Tels (again) /
575Juerd Waalboer /
576Todd Rinaldo
577
578# TODO
579
580More tests.  (Stuff I didn't think of yet.)
581
582Paragraph mode?
583
584Fixed-length mode.  Leave-blanks mode.
585
586Maybe an autolocking mode?
587
588For many common uses of the module, the read cache is a liability.
589For example, a program that inserts a single record, or that scans the
590file once, will have a cache hit rate of zero.  This suggests a major
591optimization: The cache should be initially disabled.  Here's a hybrid
592approach: Initially, the cache is disabled, but the cache code
593maintains statistics about how high the hit rate would be \*if\* it were
594enabled.  When it sees the hit rate get high enough, it enables
595itself.  The STAT comments in this code are the beginning of an
596implementation of this.
597
598Record locking with fcntl()?  Then the module might support an undo
599log and get real transactions.  What a tour de force that would be.
600
601Keeping track of the highest cached record. This would allow reads-in-a-row
602to skip the cache lookup faster (if reading from 1..N with empty cache at
603start, the last cached value will be always N-1).
604
605More tests.
606