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 # 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
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
297 (This is an advanced feature. Skip this section on first reading.)
298
299 Normally, modifying a "Tie::File" array writes to the underlying file
300 immediately. Every assignment like "$a[3] = ..." rewrites as much of
301 the file as is necessary; typically, everything from line 3 through the
302 end will need to be rewritten. This is the simplest and most
303 transparent behavior. Performance even for large files is reasonably
304 good.
305
306 However, under some circumstances, this behavior may be excessively
307 slow. For example, suppose you have a million-record file, and you
308 want to do:
309
310 for (@FILE) {
311 $_ = "> $_";
312 }
313
314 The first time through the loop, you will rewrite the entire file, from
315 line 0 through the end. The second time through the loop, you will
316 rewrite the entire file from line 1 through the end. The third time
317 through the loop, you will rewrite the entire file from line 2 to the
318 end. And so on.
319
320 If the performance in such cases is unacceptable, you may defer the
321 actual writing, and then have it done all at once. The following loop
322 will perform much better for large files:
323
324 (tied @a)->defer;
325 for (@a) {
326 $_ = "> $_";
327 }
328 (tied @a)->flush;
329
330 If "Tie::File"'s memory limit is large enough, all the writing will
331 done in memory. Then, when you call "->flush", the entire file will be
332 rewritten in a single pass.
333
334 (Actually, the preceding discussion is something of a fib. You don't
335 need to enable deferred writing to get good performance for this common
336 case, because "Tie::File" will do it for you automatically unless you
337 specifically tell it not to. See "Autodeferring", below.)
338
339 Calling "->flush" returns the array to immediate-write mode. If you
340 wish to discard the deferred writes, you may call "->discard" instead
341 of "->flush". Note that in some cases, some of the data will have been
342 written already, and it will be too late for "->discard" to discard all
343 the changes. Support for "->discard" may be withdrawn in a future
344 version of "Tie::File".
345
346 Deferred writes are cached in memory up to the limit specified by the
347 "dw_size" option (see above). If the deferred-write buffer is full and
348 you try to write still more deferred data, the buffer will be flushed.
349 All buffered data will be written immediately, the buffer will be
350 emptied, and the now-empty space will be used for future deferred
351 writes.
352
353 If the deferred-write buffer isn't yet full, but the total size of the
354 buffer and the read cache would exceed the "memory" limit, the oldest
355 records will be expired from the read cache until the total size is
356 under the limit.
357
358 "push", "pop", "shift", "unshift", and "splice" cannot be deferred.
359 When you perform one of these operations, any deferred data is written
360 to the file and the operation is performed immediately. This may
361 change in a future version.
362
363 If you resize the array with deferred writing enabled, the file will be
364 resized immediately, but deferred records will not be written. This
365 has a surprising consequence: "@a = (...)" erases the file immediately,
366 but the writing of the actual data is deferred. This might be a bug.
367 If it is a bug, it will be fixed in a future version.
368
369 Autodeferring
370 "Tie::File" tries to guess when deferred writing might be helpful, and
371 to turn it on and off automatically.
372
373 for (@a) {
374 $_ = "> $_";
375 }
376
377 In this example, only the first two assignments will be done
378 immediately; after this, all the changes to the file will be deferred
379 up to the user-specified memory limit.
380
381 You should usually be able to ignore this and just use the module
382 without thinking about deferring. However, special applications may
383 require fine control over which writes are deferred, or may require
384 that all writes be immediate. To disable the autodeferment feature,
385 use
386
387 (tied @o)->autodefer(0);
388
389 or
390
391 tie @array, 'Tie::File', $file, autodefer => 0;
392
393 Similarly, "->autodefer(1)" re-enables autodeferment, and
394 "->autodefer()" recovers the current value of the autodefer setting.
395
397 Caching and deferred writing are inappropriate if you want the same
398 file to be accessed simultaneously from more than one process. Other
399 optimizations performed internally by this module are also incompatible
400 with concurrent access. A future version of this module will support a
401 "concurrent => 1" option that enables safe concurrent access.
402
403 Previous versions of this documentation suggested using "memory => 0"
404 for safe concurrent access. This was mistaken. Tie::File will not
405 support safe concurrent access before version 0.96.
406
408 (That's Latin for 'warnings'.)
409
410 · Reasonable effort was made to make this module efficient.
411 Nevertheless, changing the size of a record in the middle of a
412 large file will always be fairly slow, because everything after the
413 new record must be moved.
414
415 · The behavior of tied arrays is not precisely the same as for
416 regular arrays. For example:
417
418 # This DOES print "How unusual!"
419 undef $a[10]; print "How unusual!\n" if defined $a[10];
420
421 "undef"-ing a "Tie::File" array element just blanks out the
422 corresponding record in the file. When you read it back again,
423 you'll get the empty string, so the supposedly-"undef"'ed value
424 will be defined. Similarly, if you have "autochomp" disabled, then
425
426 # This DOES print "How unusual!" if 'autochomp' is disabled
427 undef $a[10];
428 print "How unusual!\n" if $a[10];
429
430 Because when "autochomp" is disabled, $a[10] will read back as "\n"
431 (or whatever the record separator string is.)
432
433 There are other minor differences, particularly regarding "exists"
434 and "delete", but in general, the correspondence is extremely
435 close.
436
437 · I have supposed that since this module is concerned with file I/O,
438 almost all normal use of it will be heavily I/O bound. This means
439 that the time to maintain complicated data structures inside the
440 module will be dominated by the time to actually perform the I/O.
441 When there was an opportunity to spend CPU time to avoid doing I/O,
442 I usually tried to take it.
443
444 · You might be tempted to think that deferred writing is like
445 transactions, with "flush" as "commit" and "discard" as "rollback",
446 but it isn't, so don't.
447
448 · There is a large memory overhead for each record offset and for
449 each cache entry: about 310 bytes per cached data record, and about
450 21 bytes per offset table entry.
451
452 The per-record overhead will limit the maximum number of records
453 you can access per file. Note that accessing the length of the
454 array via "$x = scalar @tied_file" accesses all records and stores
455 their offsets. The same for "foreach (@tied_file)", even if you
456 exit the loop early.
457
459 This version promises absolutely nothing about the internals, which may
460 change without notice. A future version of the module will have a
461 well-defined and stable subclassing API.
462
464 People sometimes point out that DB_File will do something similar, and
465 ask why "Tie::File" module is necessary.
466
467 There are a number of reasons that you might prefer "Tie::File". A
468 list is available at "http://perl.plover.com/TieFile/why-not-DB_File".
469
471 Mark Jason Dominus
472
473 To contact the author, send email to: "mjd-perl-tiefile+@plover.com"
474
475 To receive an announcement whenever a new version of this module is
476 released, send a blank email message to
477 "mjd-perl-tiefile-subscribe@plover.com".
478
479 The most recent version of this module, including documentation and any
480 news of importance, will be available at
481
482 http://perl.plover.com/TieFile/
483
485 "Tie::File" version 0.96 is copyright (C) 2003 Mark Jason Dominus.
486
487 This library is free software; you may redistribute it and/or modify it
488 under the same terms as Perl itself.
489
490 These terms are your choice of any of (1) the Perl Artistic Licence, or
491 (2) version 2 of the GNU General Public License as published by the
492 Free Software Foundation, or (3) any later version of the GNU General
493 Public License.
494
495 This library is distributed in the hope that it will be useful, but
496 WITHOUT ANY WARRANTY; without even the implied warranty of
497 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
498 General Public License for more details.
499
500 You should have received a copy of the GNU General Public License along
501 with this library program; it should be in the file "COPYING". If not,
502 write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
503 Floor, Boston, MA 02110-1301, USA
504
505 For licensing inquiries, contact the author at:
506
507 Mark Jason Dominus
508 255 S. Warnock St.
509 Philadelphia, PA 19107
510
512 "Tie::File" version 0.98 comes with ABSOLUTELY NO WARRANTY. For
513 details, see the license.
514
516 Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the
517 core when I hadn't written it yet, and for generally being helpful,
518 supportive, and competent. (Usually the rule is "choose any one.")
519 Also big thanks to Abhijit Menon-Sen for all of the same things.
520
521 Special thanks to Craig Berry and Peter Prymmer (for VMS portability
522 help), Randy Kobes (for Win32 portability help), Clinton Pierce and
523 Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond
524 the call of duty), Michael G Schwern (for testing advice), and the rest
525 of the CPAN testers (for testing generally).
526
527 Special thanks to Tels for suggesting several speed and memory
528 optimizations.
529
530 Additional thanks to: Edward Avis / Mattia Barbon / Tom Christiansen /
531 Gerrit Haase / Gurusamy Sarathy / Jarkko Hietaniemi (again) / Nikola
532 Knezevic / John Kominetz / Nick Ing-Simmons / Tassilo von Parseval / H.
533 Dieter Pearcey / Slaven Rezic / Eric Roode / Peter Scott / Peter Somu /
534 Autrijus Tang (again) / Tels (again) / Juerd Waalboer / Todd Rinaldo
535
537 More tests. (Stuff I didn't think of yet.)
538
539 Paragraph mode?
540
541 Fixed-length mode. Leave-blanks mode.
542
543 Maybe an autolocking mode?
544
545 For many common uses of the module, the read cache is a liability. For
546 example, a program that inserts a single record, or that scans the file
547 once, will have a cache hit rate of zero. This suggests a major
548 optimization: The cache should be initially disabled. Here's a hybrid
549 approach: Initially, the cache is disabled, but the cache code
550 maintains statistics about how high the hit rate would be *if* it were
551 enabled. When it sees the hit rate get high enough, it enables itself.
552 The STAT comments in this code are the beginning of an implementation
553 of this.
554
555 Record locking with fcntl()? Then the module might support an undo log
556 and get real transactions. What a tour de force that would be.
557
558 Keeping track of the highest cached record. This would allow reads-in-
559 a-row to skip the cache lookup faster (if reading from 1..N with empty
560 cache at start, the last cached value will be always N-1).
561
562 More tests.
563
564
565
566perl v5.26.3 2018-03-01 Tie::File(3pm)