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