6 use Fcntl 'O_CREAT', 'O_RDWR', 'LOCK_EX', 'O_WRONLY', 'O_RDONLY';
7 sub O_ACCMODE () { O_RDONLY | O_RDWR | O_WRONLY }
10 my $DEFAULT_MEMORY_SIZE = 1<<21; # 2 megabytes
11 my $DEFAULT_AUTODEFER_THRESHHOLD = 3; # 3 records
12 my $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD = 65536; # 16 disk blocksful
14 my %good_opt = map {$_ => 1, "-$_" => 1}
15 qw(memory dw_size mode recsep discipline autodefer autochomp);
19 croak "usage: tie \@array, $_[0], filename, [option => value]...";
21 my ($pack, $file, %opts) = @_;
23 # transform '-foo' keys into 'foo' keys
24 for my $key (keys %opts) {
25 unless ($good_opt{$key}) {
26 croak("$pack: Unrecognized option '$key'\n");
29 if ($key =~ s/^-+//) {
30 $opts{$key} = delete $opts{$okey};
34 unless (defined $opts{memory}) {
35 # default is the larger of the default cache size and the
36 # deferred-write buffer size (if specified)
37 $opts{memory} = $DEFAULT_MEMORY_SIZE;
38 $opts{memory} = $opts{dw_size}
39 if defined $opts{dw_size} && $opts{dw_size} > $DEFAULT_MEMORY_SIZE;
42 $opts{dw_size} = $opts{memory} unless defined $opts{dw_size};
43 if ($opts{dw_size} > $opts{memory}) {
44 croak("$pack: dw_size may not be larger than total memory allocation\n");
46 # are we in deferred-write mode?
47 $opts{defer} = 0 unless defined $opts{defer};
48 $opts{deferred} = {}; # no records are presently deferred
49 $opts{deferred_s} = 0; # count of total bytes in ->{deferred}
50 $opts{deferred_max} = -1; # empty
52 # the cache is a hash instead of an array because it is likely to be
54 $opts{cache} = Tie::File::Cache->new($opts{memory});
56 # autodeferment is enabled by default
57 $opts{autodefer} = 1 unless defined $opts{autodefer};
58 $opts{autodeferring} = 0; # but is not initially active
59 $opts{ad_history} = [];
60 $opts{autodefer_threshhold} = $DEFAULT_AUTODEFER_THRESHHOLD
61 unless defined $opts{autodefer_threshhold};
62 $opts{autodefer_filelen_threshhold} = $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD
63 unless defined $opts{autodefer_filelen_threshhold};
66 $opts{filename} = $file;
67 unless (defined $opts{recsep}) {
68 $opts{recsep} = _default_recsep();
70 $opts{recseplen} = length($opts{recsep});
71 if ($opts{recseplen} == 0) {
72 croak "Empty record separator not supported by $pack";
75 $opts{autochomp} = 1 unless defined $opts{autochomp};
77 $opts{mode} = O_CREAT|O_RDWR unless defined $opts{mode};
78 $opts{rdonly} = (($opts{mode} & O_ACCMODE) == O_RDONLY);
79 $opts{sawlastrec} = undef;
83 if (UNIVERSAL::isa($file, 'GLOB')) {
84 # We use 1 here on the theory that some systems
85 # may not indicate failure if we use 0.
86 # MSWin32 does not indicate failure with 0, but I don't know if
87 # it will indicate failure with 1 or not.
88 unless (seek $file, 1, SEEK_SET) {
89 croak "$pack: your filehandle does not appear to be seekable";
91 seek $file, 0, SEEK_SET # put it back
92 $fh = $file; # setting binmode is the user's problem
94 croak "usage: tie \@array, $pack, filename, [option => value]...";
96 $fh = \do { local *FH }; # only works in 5.005 and later
97 sysopen $fh, $file, $opts{mode}, 0666 or return;
100 { my $ofh = select $fh; $| = 1; select $ofh } # autoflush on write
101 if (defined $opts{discipline} && $] >= 5.006) {
102 # This avoids a compile-time warning under 5.005
103 eval 'binmode($fh, $opts{discipline})';
104 croak $@ if $@ =~ /unknown discipline/i;
109 bless \%opts => $pack;
116 # check the defer buffer
117 if ($self->_is_deferring && exists $self->{deferred}{$n}) {
118 $rec = $self->{deferred}{$n};
120 $rec = $self->_fetch($n);
123 $self->_chomp1($rec);
126 # Chomp many records in-place; return nothing useful
129 return unless $self->{autochomp};
130 if ($self->{autochomp}) {
133 substr($_, - $self->{recseplen}) = "";
138 # Chomp one record in-place; return modified record
140 my ($self, $rec) = @_;
141 return $rec unless $self->{autochomp};
142 return unless defined $rec;
143 substr($rec, - $self->{recseplen}) = "";
150 # check the record cache
151 { my $cached = $self->{cache}->lookup($n);
152 return $cached if defined $cached;
155 if ($#{$self->{offsets}} < $n) {
156 return if $self->{eof};
157 my $o = $self->_fill_offsets_to($n);
158 # If it's still undefined, there is no such record, so return 'undef'
159 return unless defined $o;
162 my $fh = $self->{FH};
163 $self->_seek($n); # we can do this now that offsets is populated
164 my $rec = $self->_read_record;
166 # If we happen to have just read the first record, check to see if
167 # the length of the record matches what 'tell' says. If not, Tie::File
168 # won't work, and should drop dead.
170 # if ($n == 0 && defined($rec) && tell($self->{fh}) != length($rec)) {
171 # if (defined $self->{discipline}) {
172 # croak "I/O discipline $self->{discipline} not supported";
174 # croak "File encoding not supported";
178 $self->{cache}->insert($n, $rec) if defined $rec && not $self->{flushing};
183 my ($self, $n, $rec) = @_;
184 die "STORE called from _check_integrity!" if $DIAGNOSTIC;
186 $self->_fixrecs($rec);
188 if ($self->{autodefer}) {
189 $self->_annotate_ad_history($n);
192 return $self->_store_deferred($n, $rec) if $self->_is_deferring;
195 # We need this to decide whether the new record will fit
196 # It incidentally populates the offsets table
197 # Note we have to do this before we alter the cache
198 # 20020324 Wait, but this DOES alter the cache. TODO BUG?
199 my $oldrec = $self->_fetch($n);
201 if (defined($self->{cache}->lookup($n))) {
202 $self->{cache}->update($n, $rec);
205 if (not defined $oldrec) {
206 # We're storing a record beyond the end of the file
207 $self->_extend_file_to($n+1);
208 $oldrec = $self->{recsep};
210 my $len_diff = length($rec) - length($oldrec);
212 # length($oldrec) here is not consistent with text mode TODO XXX BUG
213 $self->_twrite($rec, $self->{offsets}[$n], length($oldrec));
215 # now update the offsets
216 # array slice goes from element $n+1 (the first one to move)
218 for (@{$self->{offsets}}[$n+1 .. $#{$self->{offsets}}]) {
223 sub _store_deferred {
224 my ($self, $n, $rec) = @_;
225 $self->{cache}->remove($n);
226 my $old_deferred = $self->{deferred}{$n};
228 if (defined $self->{deferred_max} && $n > $self->{deferred_max}) {
229 $self->{deferred_max} = $n;
231 $self->{deferred}{$n} = $rec;
233 my $len_diff = length($rec);
234 $len_diff -= length($old_deferred) if defined $old_deferred;
235 $self->{deferred_s} += $len_diff;
236 $self->{cache}->adj_limit(-$len_diff);
237 if ($self->{deferred_s} > $self->{dw_size}) {
239 } elsif ($self->_cache_too_full) {
244 # Remove a single record from the deferred-write buffer without writing it
245 # The record need not be present
246 sub _delete_deferred {
248 my $rec = delete $self->{deferred}{$n};
249 return unless defined $rec;
251 if (defined $self->{deferred_max}
252 && $n == $self->{deferred_max}) {
253 undef $self->{deferred_max};
256 $self->{deferred_s} -= length $rec;
257 $self->{cache}->adj_limit(length $rec);
262 my $n = $#{$self->{offsets}};
263 # 20020317 Change this to binary search
264 unless ($self->{eof}) {
265 while (defined ($self->_fill_offsets_to($n+1))) {
269 my $top_deferred = $self->_defer_max;
270 $n = $top_deferred+1 if defined $top_deferred && $n < $top_deferred+1;
275 my ($self, $len) = @_;
277 if ($self->{autodefer}) {
278 $self->_annotate_ad_history('STORESIZE');
281 my $olen = $self->FETCHSIZE;
282 return if $len == $olen; # Woo-hoo!
286 if ($self->_is_deferring) {
287 for ($olen .. $len-1) {
288 $self->_store_deferred($_, $self->{recsep});
291 $self->_extend_file_to($len);
297 if ($self->_is_deferring) {
298 # TODO maybe replace this with map-plus-assignment?
299 for (grep $_ >= $len, keys %{$self->{deferred}}) {
300 $self->_delete_deferred($_);
302 $self->{deferred_max} = $len-1;
307 $#{$self->{offsets}} = $len;
308 # $self->{offsets}[0] = 0; # in case we just chopped this
310 $self->{cache}->remove(grep $_ >= $len, $self->{cache}->ckeys);
315 $self->SPLICE($self->FETCHSIZE, scalar(@_), @_);
316 # $self->FETCHSIZE; # av.c takes care of this for me
321 my $size = $self->FETCHSIZE;
322 return if $size == 0;
323 # print STDERR "# POPPITY POP POP POP\n";
324 scalar $self->SPLICE($size-1, 1);
329 scalar $self->SPLICE(0, 1);
334 $self->SPLICE(0, 0, @_);
335 # $self->FETCHSIZE; # av.c takes care of this for me
341 if ($self->{autodefer}) {
342 $self->_annotate_ad_history('CLEAR');
347 $self->{cache}->set_limit($self->{memory});
348 $self->{cache}->empty;
349 @{$self->{offsets}} = (0);
350 %{$self->{deferred}}= ();
351 $self->{deferred_s} = 0;
352 $self->{deferred_max} = -1;
358 # No need to pre-extend anything in this case
359 return if $self->_is_deferring;
361 $self->_fill_offsets_to($n);
362 $self->_extend_file_to($n);
368 if ($self->{autodefer}) {
369 $self->_annotate_ad_history('DELETE');
372 my $lastrec = $self->FETCHSIZE-1;
373 my $rec = $self->FETCH($n);
374 $self->_delete_deferred($n) if $self->_is_deferring;
375 if ($n == $lastrec) {
378 $#{$self->{offsets}}--;
379 $self->{cache}->remove($n);
380 # perhaps in this case I should also remove trailing null records?
382 # Note that delete @a[-3..-1] deletes the records in the wrong order,
383 # so we only chop the very last one out of the file. We could repair this
384 # by tracking deleted records inside the object.
385 } elsif ($n < $lastrec) {
386 $self->STORE($n, "");
393 return 1 if exists $self->{deferred}{$n};
394 $self->_fill_offsets_to($n); # I think this is unnecessary
395 $n < $self->FETCHSIZE;
401 if ($self->{autodefer}) {
402 $self->_annotate_ad_history('SPLICE');
405 $self->_flush if $self->_is_deferring; # move this up?
407 $self->_chomp(my @a = $self->_splice(@_));
410 $self->_chomp1(scalar $self->_splice(@_));
416 $self->flush if $self->_is_deferring;
417 $self->{cache}->delink if defined $self->{cache}; # break circular link
421 my ($self, $pos, $nrecs, @data) = @_;
424 $pos = 0 unless defined $pos;
426 # Deal with negative and other out-of-range positions
427 # Also set default for $nrecs
429 my $oldsize = $self->FETCHSIZE;
430 $nrecs = $oldsize unless defined $nrecs;
436 croak "Modification of non-creatable array value attempted, subscript $oldpos";
440 if ($pos > $oldsize) {
442 $pos = $oldsize; # This is what perl does for normal arrays
445 # The manual is very unclear here
447 $nrecs = $oldsize - $pos + $nrecs;
448 $nrecs = 0 if $nrecs < 0;
452 $self->_fixrecs(@data);
453 my $data = join '', @data;
454 my $datalen = length $data;
457 # compute length of data being removed
458 for ($pos .. $pos+$nrecs-1) {
459 last unless defined $self->_fill_offsets_to($_);
460 my $rec = $self->_fetch($_);
461 last unless defined $rec;
464 # Why don't we just use length($rec) here?
465 # Because that record might have come from the cache. _splice
466 # might have been called to flush out the deferred-write records,
467 # and in this case length($rec) is the length of the record to be
468 # *written*, not the length of the actual record in the file. But
469 # the offsets are still true. 20020322
470 $oldlen += $self->{offsets}[$_+1] - $self->{offsets}[$_]
471 if defined $self->{offsets}[$_+1];
475 $self->_twrite($data, $self->{offsets}[$pos], $oldlen);
477 # update the offsets table part 1
478 # compute the offsets of the new records:
481 push @new_offsets, $self->{offsets}[$pos];
482 for (0 .. $#data-1) {
483 push @new_offsets, $new_offsets[-1] + length($data[$_]);
487 # If we're about to splice out the end of the offsets table...
488 if ($pos + $nrecs >= @{$self->{offsets}}) {
489 $self->{eof} = 0; # ... the table is no longer complete
491 splice(@{$self->{offsets}}, $pos, $nrecs, @new_offsets);
493 # update the offsets table part 2
494 # adjust the offsets of the following old records
495 for ($pos+@data .. $#{$self->{offsets}}) {
496 $self->{offsets}[$_] += $datalen - $oldlen;
498 # If we scrubbed out all known offsets, regenerate the trivial table
499 # that knows that the file does indeed start at 0.
500 $self->{offsets}[0] = 0 unless @{$self->{offsets}};
501 # If the file got longer, the offsets table is no longer complete
502 $self->{eof} = 0 if @data > $nrecs;
505 # Perhaps the following cache foolery could be factored out
506 # into a bunch of mor opaque cache functions. For example,
507 # it's odd to delete a record from the cache and then remove
508 # it from the LRU queue later on; there should be a function to
511 # update the read cache, part 1
513 for ($pos .. $pos+$nrecs-1) {
514 my $new = $data[$_-$pos];
516 $self->{cache}->update($_, $new);
518 $self->{cache}->remove($_);
522 # update the read cache, part 2
523 # moved records - records past the site of the change
524 # need to be renumbered
525 # Maybe merge this with the previous block?
527 my @oldkeys = grep $_ >= $pos + $nrecs, $self->{cache}->ckeys;
528 my @newkeys = map $_-$nrecs+@data, @oldkeys;
529 $self->{cache}->rekey(\@oldkeys, \@newkeys);
532 # Now there might be too much data in the cache, if we spliced out
533 # some short records and spliced in some long ones. If so, flush
537 # Yes, the return value of 'splice' *is* actually this complicated
538 wantarray ? @result : @result ? $result[-1] : undef;
541 # write data into the file
542 # $data is the data to be written.
543 # it should be written at position $pos, and should overwrite
544 # exactly $len of the following bytes.
545 # Note that if length($data) > $len, the subsequent bytes will have to
546 # be moved up, and if length($data) < $len, they will have to
549 my ($self, $data, $pos, $len) = @_;
551 unless (defined $pos) {
552 die "\$pos was undefined in _twrite";
555 my $len_diff = length($data) - $len;
557 if ($len_diff == 0) { # Woo-hoo!
558 my $fh = $self->{fh};
560 $self->_write_record($data);
561 return; # well, that was easy.
564 # the two records are of different lengths
565 # our strategy here: rewrite the tail of the file,
566 # reading ahead one buffer at a time
567 # $bufsize is required to be at least as large as the data we're overwriting
568 my $bufsize = _bufsize($len_diff);
569 my ($writepos, $readpos) = ($pos, $pos+$len);
573 # Seems like there ought to be a way to avoid the repeated code
574 # and the special case here. The read(1) is also a little weird.
577 $self->_seekb($readpos);
578 my $br = read $self->{fh}, $next_block, $bufsize;
579 $more_data = read $self->{fh}, my($dummy), 1;
580 $self->_seekb($writepos);
581 $self->_write_record($data);
583 $writepos += length $data;
585 } while $more_data; # BUG XXX TODO how could this have worked?
586 $self->_seekb($writepos);
587 $self->_write_record($next_block);
589 # There might be leftover data at the end of the file
590 $self->_chop_file if $len_diff < 0;
593 # If a record does not already end with the appropriate terminator
594 # string, append one.
598 $_ = "" unless defined $_;
599 $_ .= $self->{recsep}
600 unless substr($_, - $self->{recseplen}) eq $self->{recsep};
605 ################################################################
607 # Basic read, write, and seek
610 # seek to the beginning of record #$n
611 # Assumes that the offsets table is already correctly populated
613 # Note that $n=-1 has a special meaning here: It means the start of
614 # the last known record; this may or may not be the very last record
615 # in the file, depending on whether the offsets table is fully populated.
619 my $o = $self->{offsets}[$n];
621 or confess("logic error: undefined offset for record $n");
622 seek $self->{fh}, $o, SEEK_SET
623 or die "Couldn't seek filehandle: $!"; # "Should never happen."
628 seek $self->{fh}, $b, SEEK_SET
629 or die "Couldn't seek filehandle: $!"; # "Should never happen."
632 # populate the offsets table up to the beginning of record $n
633 # return the offset of record $n
634 sub _fill_offsets_to {
637 return $self->{offsets}[$n] if $self->{eof};
639 my $fh = $self->{fh};
640 local *OFF = $self->{offsets};
643 until ($#OFF >= $n) {
645 $self->_seek(-1); # tricky -- see comment at _seek
646 $rec = $self->_read_record;
651 return; # It turns out there is no such record
655 # we have now read all the records up to record n-1,
656 # so we can return the offset of record n
660 # assumes that $rec is already suitably terminated
662 my ($self, $rec) = @_;
663 my $fh = $self->{fh};
666 or die "Couldn't write record: $!"; # "Should never happen."
667 # $self->{_written} += length($rec);
673 { local $/ = $self->{recsep};
674 my $fh = $self->{fh};
677 return unless defined $rec;
678 if (! $self->{sawlastrec} &&
679 substr($rec, -$self->{recseplen}) ne $self->{recsep}) {
680 # improperly terminated final record --- quietly fix it.
681 # my $ac = substr($rec, -$self->{recseplen});
683 $self->{sawlastrec} = 1;
684 unless ($self->{rdonly}) {
686 my $fh = $self->{fh};
687 print $fh $self->{recsep};
689 $rec .= $self->{recsep};
691 # $self->{_read} += length($rec) if defined $rec;
697 @{$self}{'_read', '_written'};
700 ################################################################
702 # Read cache management
706 $self->{cache}->reduce_size_to($self->{memory} - $self->{deferred_s});
709 sub _cache_too_full {
711 $self->{cache}->bytes + $self->{deferred_s} >= $self->{memory};
714 ################################################################
716 # File custodial services
720 # We have read to the end of the file and have the offsets table
721 # entirely populated. Now we need to write a new record beyond
722 # the end of the file. We prepare for this by writing
723 # empty records into the file up to the position we want
725 # assumes that the offsets table already contains the offset of record $n,
726 # if it exists, and extends to the end of the file if not.
727 sub _extend_file_to {
729 $self->_seek(-1); # position after the end of the last record
730 my $pos = $self->{offsets}[-1];
732 # the offsets table has one entry more than the total number of records
733 my $extras = $n - $#{$self->{offsets}};
735 # Todo : just use $self->{recsep} x $extras here?
736 while ($extras-- > 0) {
737 $self->_write_record($self->{recsep});
738 push @{$self->{offsets}}, tell $self->{fh};
742 # Truncate the file at the current position
745 truncate $self->{fh}, tell($self->{fh});
749 # compute the size of a buffer suitable for moving
750 # all the data in a file forward $n bytes
751 # ($n may be negative)
752 # The result should be at least $n.
755 return 8192 if $n < 0;
757 $b += 8192 if $n & 8191;
761 ################################################################
763 # Miscellaneous public methods
768 my ($self, $op) = @_;
770 my $pack = ref $self;
771 croak "Usage: $pack\->flock([OPERATION])";
773 my $fh = $self->{fh};
774 $op = LOCK_EX unless defined $op;
778 # Get/set autochomp option
782 my $old = $self->{autochomp};
783 $self->{autochomp} = shift;
790 ################################################################
792 # Matters related to deferred writing
798 $self->_stop_autodeferring;
799 @{$self->{ad_history}} = ();
803 # Flush deferred writes
805 # This could be better optimized to write the file in one pass, instead
806 # of one pass per block of records. But that will require modifications
807 # to _twrite, so I should have a good _twite test suite first.
817 my @writable = sort {$a<=>$b} (keys %{$self->{deferred}});
820 # gather all consecutive records from the front of @writable
821 my $first_rec = shift @writable;
822 my $last_rec = $first_rec+1;
823 ++$last_rec, shift @writable while @writable && $last_rec == $writable[0];
825 $self->_fill_offsets_to($last_rec);
826 $self->_extend_file_to($last_rec);
827 $self->_splice($first_rec, $last_rec-$first_rec+1,
828 @{$self->{deferred}}{$first_rec .. $last_rec});
831 $self->_discard; # clear out defered-write-cache
834 # Discard deferred writes and disable future deferred writes
841 # Discard deferred writes, but retain old deferred writing mode
844 %{$self->{deferred}} = ();
845 $self->{deferred_s} = 0;
846 $self->{deferred_max} = -1;
847 $self->{cache}->set_limit($self->{memory});
850 # Deferred writing is enabled, either explicitly ($self->{defer})
851 # or automatically ($self->{autodeferring})
854 $self->{defer} || $self->{autodeferring};
857 # The largest record number of any deferred record
860 return $self->{deferred_max} if defined $self->{deferred_max};
862 for my $key (keys %{$self->{deferred}}) {
863 $max = $key if $key > $max;
865 $self->{deferred_max} = $max;
869 ################################################################
871 # Matters related to autodeferment
874 # Get/set autodefer option
878 my $old = $self->{autodefer};
879 $self->{autodefer} = shift;
881 $self->_stop_autodeferring;
882 @{$self->{ad_history}} = ();
890 # The user is trying to store record #$n Record that in the history,
891 # and then enable (or disable) autodeferment if that seems useful.
892 # Note that it's OK for $n to be a non-number, as long as the function
893 # is prepared to deal with that. Nobody else looks at the ad_history.
895 # Now, what does the ad_history mean, and what is this function doing?
896 # Essentially, the idea is to enable autodeferring when we see that the
897 # user has made three consecutive STORE calls to three consecutive records.
898 # ("Three" is actually ->{autodefer_threshhold}.)
899 # A STORE call for record #$n inserts $n into the autodefer history,
900 # and if the history contains three consecutive records, we enable
901 # autodeferment. An ad_history of [X, Y] means that the most recent
902 # STOREs were for records X, X+1, ..., Y, in that order.
904 # Inserting a nonconsecutive number erases the history and starts over.
906 # Performing a special operation like SPLICE erases the history.
908 # There's one special case: CLEAR means that CLEAR was just called.
909 # In this case, we prime the history with [-2, -1] so that if the next
910 # write is for record 0, autodeferring goes on immediately. This is for
911 # the common special case of "@a = (...)".
913 sub _annotate_ad_history {
915 return unless $self->{autodefer}; # feature is disabled
916 return if $self->{defer}; # already in explicit defer mode
917 return unless $self->{offsets}[-1] >= $self->{autodefer_filelen_threshhold};
919 local *H = $self->{ad_history};
921 @H = (-2, -1); # prime the history with fake records
922 $self->_stop_autodeferring;
923 } elsif ($n =~ /^\d+$/) {
927 if ($H[1] == $n-1) { # another consecutive record
929 if ($H[1] - $H[0] + 1 >= $self->{autodefer_threshhold}) {
930 $self->{autodeferring} = 1;
932 } else { # nonconsecutive- erase and start over
934 $self->_stop_autodeferring;
937 } else { # SPLICE or STORESIZE or some such
939 $self->_stop_autodeferring;
943 # If autodferring was enabled, cut it out and discard the history
944 sub _stop_autodeferring {
946 if ($self->{autodeferring}) {
949 $self->{autodeferring} = 0;
952 ################################################################
955 # This is NOT a method. It is here for two reasons:
956 # 1. To factor a fairly complicated block out of the constructor
957 # 2. To provide access for the test suite, which need to be sure
958 # files are being written properly.
959 sub _default_recsep {
961 if ($^O eq 'MSWin32') { # Dos too?
962 # Windows users expect files to be terminated with \r\n
963 # But $/ is set to \n instead
964 # Note that this also transforms \n\n into \r\n\r\n.
966 $recsep =~ s/\n/\r\n/g;
971 # Utility function for _check_integrity
979 # Given a file, make sure the cache is consistent with the
980 # file contents and the internal data structures are consistent with
981 # each other. Returns true if everything checks out, false if not
983 # The $file argument is no longer used. It is retained for compatibility
984 # with the existing test suite.
985 sub _check_integrity {
986 my ($self, $file, $warn) = @_;
987 my $rsl = $self->{recseplen};
988 my $rs = $self->{recsep};
990 local *_; # local $_ does not work here
991 local $DIAGNOSTIC = 1;
993 if (not defined $rs) {
994 _ci_warn("recsep is undef!");
996 } elsif ($rs eq "") {
997 _ci_warn("recsep is empty!");
999 } elsif ($rsl != length $rs) {
1000 my $ln = length $rs;
1001 _ci_warn("recsep <$rs> has length $ln, should be $rsl");
1005 if (not defined $self->{offsets}[0]) {
1006 _ci_warn("offset 0 is missing!");
1009 } elsif ($self->{offsets}[0] != 0) {
1010 _ci_warn("rec 0: offset <$self->{offsets}[0]> s/b 0!");
1016 local *F = $self->{fh};
1017 seek F, 0, SEEK_SET;
1023 my $cached = $self->{cache}->_produce($n);
1024 my $offset = $self->{offsets}[$.];
1026 if (defined $offset && $offset != $ao) {
1027 _ci_warn("rec $n: offset <$offset> actual <$ao>");
1030 if (defined $cached && $_ ne $cached && ! $self->{deferred}{$n}) {
1032 _ci_warn("rec $n: cached <$cached> actual <$_>");
1034 if (defined $cached && substr($cached, -$rsl) ne $rs) {
1036 _ci_warn("rec $n in the cache is missing the record separator");
1038 if (! defined $offset && $self->{eof}) {
1040 _ci_warn("The offset table was marked complete, but it is missing element $.");
1043 if (@{$self->{offsets}} > $.+1) {
1045 my $n = @{$self->{offsets}};
1046 _ci_warn("The offset table has $n items, but the file has only $.");
1049 my $deferring = $self->_is_deferring;
1050 for my $n ($self->{cache}->ckeys) {
1051 my $r = $self->{cache}->_produce($n);
1052 $cached += length($r);
1053 next if $n+1 <= $.; # checked this already
1054 _ci_warn("spurious caching of record $n");
1057 my $b = $self->{cache}->bytes;
1058 if ($cached != $b) {
1059 _ci_warn("cache size is $b, should be $cached");
1064 # That cache has its own set of tests
1065 $good = 0 unless $self->{cache}->_check_integrity;
1067 # Now let's check the deferbuffer
1068 # Unless deferred writing is enabled, it should be empty
1069 if (! $self->_is_deferring && %{$self->{deferred}}) {
1070 _ci_warn("deferred writing disabled, but deferbuffer nonempty");
1074 # Any record in the deferbuffer should *not* be present in the readcache
1076 while (my ($n, $r) = each %{$self->{deferred}}) {
1077 $deferred_s += length($r);
1078 if (defined $self->{cache}->_produce($n)) {
1079 _ci_warn("record $n is in the deferbuffer *and* the readcache");
1082 if (substr($r, -$rsl) ne $rs) {
1083 _ci_warn("rec $n in the deferbuffer is missing the record separator");
1088 # Total size of deferbuffer should match internal total
1089 if ($deferred_s != $self->{deferred_s}) {
1090 _ci_warn("buffer size is $self->{deferred_s}, should be $deferred_s");
1094 # Total size of deferbuffer should not exceed the specified limit
1095 if ($deferred_s > $self->{dw_size}) {
1096 _ci_warn("buffer size is $self->{deferred_s} which exceeds the limit of $self->{dw_size}");
1100 # Total size of cached data should not exceed the specified limit
1101 if ($deferred_s + $cached > $self->{memory}) {
1102 my $total = $deferred_s + $cached;
1103 _ci_warn("total stored data size is $total which exceeds the limit of $self->{memory}");
1107 # Stuff related to autodeferment
1108 if (!$self->{autodefer} && @{$self->{ad_history}}) {
1109 _ci_warn("autodefer is disabled, but ad_history is nonempty");
1112 if ($self->{autodeferring} && $self->{defer}) {
1113 _ci_warn("both autodeferring and explicit deferring are active");
1116 if (@{$self->{ad_history}} == 0) {
1117 # That's OK, no additional tests required
1118 } elsif (@{$self->{ad_history}} == 2) {
1119 my @non_number = grep !/^-?\d+$/, @{$self->{ad_history}};
1123 $msg = "ad_history contains non-numbers (@{$self->{ad_history}})";
1127 } elsif ($self->{ad_history}[1] < $self->{ad_history}[0]) {
1128 _ci_warn("ad_history has nonsensical values @{$self->{ad_history}}");
1132 _ci_warn("ad_history has bad length <@{$self->{ad_history}}>");
1139 ################################################################
1145 package Tie::File::Cache;
1146 $Tie::File::Cache::VERSION = $Tie::File::VERSION;
1147 use Carp ':DEFAULT', 'confess';
1156 my ($pack, $max) = @_;
1158 croak "missing argument to ->new" unless defined $max;
1160 bless $self => $pack;
1161 @$self = (Tie::File::Heap->new($self), {}, $max, 0);
1166 my ($self, $n) = @_;
1171 my ($self, $n) = @_;
1175 # For internal use only
1176 # Will be called by the heap structure to notify us that a certain
1177 # piece of data has moved from one heap element to another.
1178 # $k is the hash key of the item
1179 # $n is the new index into the heap at which it is stored
1180 # If $n is undefined, the item has been removed from the heap.
1182 my ($self, $k, $n) = @_;
1184 $self->[HASH]{$k} = $n;
1186 delete $self->[HASH]{$k};
1191 my ($self, $key, $val) = @_;
1193 croak "missing argument to ->insert" unless defined $key;
1194 unless (defined $self->[MAX]) {
1195 confess "undefined max" ;
1197 confess "undefined val" unless defined $val;
1198 return if length($val) > $self->[MAX];
1199 my $oldnode = $self->[HASH]{$key};
1200 if (defined $oldnode) {
1201 my $oldval = $self->[HEAP]->set_val($oldnode, $val);
1202 $self->[BYTES] -= length($oldval);
1204 $self->[HEAP]->insert($key, $val);
1206 $self->[BYTES] += length($val);
1212 my $old_data = $self->[HEAP]->popheap;
1213 return unless defined $old_data;
1214 $self->[BYTES] -= length $old_data;
1219 my ($self, @keys) = @_;
1221 for my $key (@keys) {
1222 next unless exists $self->[HASH]{$key};
1223 my $old_data = $self->[HEAP]->remove($self->[HASH]{$key});
1224 $self->[BYTES] -= length $old_data;
1225 push @result, $old_data;
1231 my ($self, $key) = @_;
1233 croak "missing argument to ->lookup" unless defined $key;
1234 if (exists $self->[HASH]{$key}) {
1235 $self->[HEAP]->lookup($self->[HASH]{$key});
1241 # For internal use only
1243 my ($self, $key) = @_;
1244 my $loc = $self->[HASH]{$key};
1245 return unless defined $loc;
1246 $self->[HEAP][$loc][2];
1249 # For internal use only
1251 my ($self, $key) = @_;
1252 $self->[HEAP]->promote($self->[HASH]{$key});
1257 %{$self->[HASH]} = ();
1259 $self->[HEAP]->empty;
1264 keys %{$self->[HASH]} == 0;
1268 my ($self, $key, $val) = @_;
1270 croak "missing argument to ->update" unless defined $key;
1271 if (length($val) > $self->[MAX]) {
1272 my $oldval = $self->remove($key);
1273 $self->[BYTES] -= length($oldval) if defined $oldval;
1274 } elsif (exists $self->[HASH]{$key}) {
1275 my $oldval = $self->[HEAP]->set_val($self->[HASH]{$key}, $val);
1276 $self->[BYTES] += length($val);
1277 $self->[BYTES] -= length($oldval) if defined $oldval;
1279 $self->[HEAP]->insert($key, $val);
1280 $self->[BYTES] += length($val);
1286 my ($self, $okeys, $nkeys) = @_;
1289 @map{@$okeys} = @$nkeys;
1290 croak "missing argument to ->rekey" unless defined $nkeys;
1291 croak "length mismatch in ->rekey arguments" unless @$nkeys == @$okeys;
1292 my %adjusted; # map new keys to heap indices
1293 # You should be able to cut this to one loop TODO XXX
1294 for (0 .. $#$okeys) {
1295 $adjusted{$nkeys->[$_]} = delete $self->[HASH]{$okeys->[$_]};
1297 while (my ($nk, $ix) = each %adjusted) {
1298 # @{$self->[HASH]}{keys %adjusted} = values %adjusted;
1299 $self->[HEAP]->rekey($ix, $nk);
1300 $self->[HASH]{$nk} = $ix;
1306 my @a = keys %{$self->[HASH]};
1315 sub reduce_size_to {
1316 my ($self, $max) = @_;
1317 until ($self->is_empty || $self->[BYTES] <= $max) {
1324 until ($self->is_empty || $self->[BYTES] <= $self->[MAX]) {
1329 # For internal use only
1332 $self->[HEAP]->expire_order;
1335 BEGIN { *_ci_warn = \&Tie::File::_ci_warn }
1337 sub _check_integrity { # For CACHE
1342 $self->[HEAP]->_check_integrity or $good = 0;
1346 for my $k (keys %{$self->[HASH]}) {
1347 if ($k ne '0' && $k !~ /^[1-9][0-9]*$/) {
1349 _ci_warn "Cache hash key <$k> is non-numeric";
1352 my $h = $self->[HASH]{$k};
1355 _ci_warn "Heap index number for key $k is undefined";
1358 _ci_warn "Heap index number for key $k is zero";
1360 my $j = $self->[HEAP][$h];
1363 _ci_warn "Heap contents key $k (=> $h) are undefined";
1365 $bytes += length($j->[2]);
1366 if ($k ne $j->[1]) {
1368 _ci_warn "Heap contents key $k (=> $h) is $j->[1], should be $k";
1375 if ($bytes != $self->[BYTES]) {
1377 _ci_warn "Total data in cache is $bytes, expected $self->[BYTES]";
1381 if ($bytes > $self->[MAX]) {
1383 _ci_warn "Total data in cache is $bytes, exceeds maximum $self->[MAX]";
1391 $self->[HEAP] = undef; # Bye bye heap
1394 ################################################################
1398 # Heap data structure for use by cache LRU routines
1400 package Tie::File::Heap;
1401 use Carp ':DEFAULT', 'confess';
1402 $Tie::File::Heap::VERSION = $Tie::File::Cache::VERSION;
1408 my ($pack, $cache) = @_;
1409 die "$pack: Parent cache object $cache does not support _heap_move method"
1410 unless eval { $cache->can('_heap_move') };
1411 my $self = [[0,$cache,0]];
1412 bless $self => $pack;
1415 # Allocate a new sequence number, larger than all previously allocated numbers
1450 $self->[0][0] = 0; # might as well reset the sequence numbers
1453 # notify the parent cache object that we moved something
1456 $self->_cache->_heap_move(@_);
1459 # Insert a piece of data into the heap with the indicated sequence number.
1460 # The item with the smallest sequence number is always at the top.
1461 # If no sequence number is specified, allocate a new one and insert the
1462 # item at the bottom.
1464 my ($self, $key, $data, $seq) = @_;
1465 $seq = $self->_nseq unless defined $seq;
1466 $self->_insert_new([$seq, $key, $data]);
1469 # Insert a new, fresh item at the bottom of the heap
1471 my ($self, $item) = @_;
1473 $i = int($i/2) until defined $self->[$i/2];
1474 $self->[$i] = $item;
1475 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1479 # Insert [$data, $seq] pair at or below item $i in the heap.
1480 # If $i is omitted, default to 1 (the top element.)
1482 my ($self, $item, $i) = @_;
1483 # $self->_check_loc($i) if defined $i;
1484 $i = 1 unless defined $i;
1485 until (! defined $self->[$i]) {
1486 if ($self->[$i][SEQ] > $item->[SEQ]) { # inserted item is older
1487 ($self->[$i], $item) = ($item, $self->[$i]);
1488 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1490 # If either is undefined, go that way. Otherwise, choose at random
1492 $dir = 0 if !defined $self->[2*$i];
1493 $dir = 1 if !defined $self->[2*$i+1];
1494 $dir = int(rand(2)) unless defined $dir;
1497 $self->[$i] = $item;
1498 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1502 # Remove the item at node $i from the heap, moving child items upwards.
1503 # The item with the smallest sequence number is always at the top.
1504 # Moving items upwards maintains this condition.
1505 # Return the removed item.
1507 my ($self, $i) = @_;
1508 $i = 1 unless defined $i;
1509 my $top = $self->[$i];
1510 return unless defined $top;
1513 my ($L, $R) = (2*$i, 2*$i+1);
1515 # If either is undefined, go the other way.
1516 # Otherwise, go towards the smallest.
1517 last unless defined $self->[$L] || defined $self->[$R];
1518 $ii = $R if not defined $self->[$L];
1519 $ii = $L if not defined $self->[$R];
1520 unless (defined $ii) {
1521 $ii = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
1524 $self->[$i] = $self->[$ii]; # Promote child to fill vacated spot
1525 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1526 $i = $ii; # Fill new vacated spot
1528 $self->[0][1]->_heap_move($top->[KEY], undef);
1539 # set the sequence number of the indicated item to a higher number
1540 # than any other item in the heap, and bubble the item down to the
1543 my ($self, $n) = @_;
1544 # $self->_check_loc($n);
1545 $self->[$n][SEQ] = $self->_nseq;
1548 my ($L, $R) = (2*$i, 2*$i+1);
1550 last unless defined $self->[$L] || defined $self->[$R];
1551 $dir = $R unless defined $self->[$L];
1552 $dir = $L unless defined $self->[$R];
1553 unless (defined $dir) {
1554 $dir = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
1556 @{$self}[$i, $dir] = @{$self}[$dir, $i];
1558 $self->[0][1]->_heap_move($self->[$_][KEY], $_) if defined $self->[$_];
1564 # Return item $n from the heap, promoting its LRU status
1566 my ($self, $n) = @_;
1567 # $self->_check_loc($n);
1568 my $val = $self->[$n];
1574 # Assign a new value for node $n, promoting it to the bottom of the heap
1576 my ($self, $n, $val) = @_;
1577 # $self->_check_loc($n);
1578 my $oval = $self->[$n][DAT];
1579 $self->[$n][DAT] = $val;
1584 # The hask key has changed for an item;
1585 # alter the heap's record of the hash key
1587 my ($self, $n, $new_key) = @_;
1588 # $self->_check_loc($n);
1589 $self->[$n][KEY] = $new_key;
1593 my ($self, $n) = @_;
1594 unless (1 || defined $self->[$n]) {
1595 confess "_check_loc($n) failed";
1599 BEGIN { *_ci_warn = \&Tie::File::_ci_warn }
1601 sub _check_integrity {
1606 unless (eval {$self->[0][1]->isa("Tie::File::Cache")}) {
1607 _ci_warn "Element 0 of heap corrupt";
1610 $good = 0 unless $self->_satisfies_heap_condition(1);
1611 for my $i (2 .. $#{$self}) {
1612 my $p = int($i/2); # index of parent node
1613 if (defined $self->[$i] && ! defined $self->[$p]) {
1614 _ci_warn "Element $i of heap defined, but parent $p isn't";
1618 if (defined $self->[$i]) {
1619 if ($seq{$self->[$i][SEQ]}) {
1620 my $seq = $self->[$i][SEQ];
1621 _ci_warn "Nodes $i and $seq{$seq} both have SEQ=$seq";
1624 $seq{$self->[$i][SEQ]} = $i;
1632 sub _satisfies_heap_condition {
1638 next unless defined $self->[$c];
1639 if ($self->[$n][SEQ] >= $self->[$c]) {
1640 _ci_warn "Node $n of heap does not predate node $c";
1643 $good = 0 unless $self->_satisfies_heap_condition($c);
1648 # Return a list of all the values, sorted by expiration order
1651 my @nodes = sort {$a->[SEQ] <=> $b->[SEQ]} $self->_nodes;
1652 map { $_->[KEY] } @nodes;
1658 return unless defined $self->[$i];
1659 ($self->[$i], $self->_nodes($i*2), $self->_nodes($i*2+1));
1662 "Cogito, ergo sum."; # don't forget to return a true value from the file
1666 Tie::File - Access the lines of a disk file via a Perl array
1670 # This file documents Tie::File version 0.93
1672 tie @array, 'Tie::File', filename or die ...;
1674 $array[13] = 'blah'; # line 13 of the file is now 'blah'
1675 print $array[42]; # display line 42 of the file
1677 $n_recs = @array; # how many records are in the file?
1678 $#array -= 2; # chop two records off the end
1682 s/PERL/Perl/g; # Replace PERL with Perl everywhere in the file
1685 # These are just like regular push, pop, unshift, shift, and splice
1686 # Except that they modify the file in the way you would expect
1688 push @array, new recs...;
1689 my $r1 = pop @array;
1690 unshift @array, new recs...;
1691 my $r1 = shift @array;
1692 @old_recs = splice @array, 3, 7, new recs...;
1694 untie @array; # all finished
1699 C<Tie::File> represents a regular text file as a Perl array. Each
1700 element in the array corresponds to a record in the file. The first
1701 line of the file is element 0 of the array; the second line is element
1704 The file is I<not> loaded into memory, so this will work even for
1707 Changes to the array are reflected in the file immediately.
1709 Lazy people and beginners may now stop reading the manual.
1713 What is a 'record'? By default, the meaning is the same as for the
1714 C<E<lt>...E<gt>> operator: It's a string terminated by C<$/>, which is
1715 probably C<"\n">. (Minor exception: on dos and Win32 systems, a
1716 'record' is a string terminated by C<"\r\n">.) You may change the
1717 definition of "record" by supplying the C<recsep> option in the C<tie>
1720 tie @array, 'Tie::File', $file, recsep => 'es';
1722 This says that records are delimited by the string C<es>. If the file
1723 contained the following data:
1725 Curse these pesky flies!\n
1727 then the C<@array> would appear to have four elements:
1734 An undefined value is not permitted as a record separator. Perl's
1735 special "paragraph mode" semantics (E<agrave> la C<$/ = "">) are not
1738 Records read from the tied array do not have the record separator
1739 string on the end; this is to allow
1741 $array[17] .= "extra";
1743 to work as expected.
1745 (See L<"autochomp">, below.) Records stored into the array will have
1746 the record separator string appended before they are written to the
1747 file, if they don't have one already. For example, if the record
1748 separator string is C<"\n">, then the following two lines do exactly
1751 $array[17] = "Cherry pie";
1752 $array[17] = "Cherry pie\n";
1754 The result is that the contents of line 17 of the file will be
1755 replaced with "Cherry pie"; a newline character will separate line 17
1756 from line 18. This means that this code will do nothing:
1760 Because the C<chomp>ed value will have the separator reattached when
1761 it is written back to the file. There is no way to create a file
1762 whose trailing record separator string is missing.
1764 Inserting records that I<contain> the record separator string is not
1765 supported by this module. It will probably produce a reasonable
1766 result, but what this result will be may change in a future version.
1767 Use 'splice' to insert records or to replace one record with several.
1771 Normally, array elements have the record separator removed, so that if
1772 the file contains the text
1778 the tied array will appear to contain C<("Gold", "Frankincense",
1779 "Myrrh")>. If you set C<autochomp> to a false value, the record
1780 separator will not be removed. If the file above was tied with
1782 tie @gifts, "Tie::File", $gifts, autochomp => 0;
1784 then the array C<@gifts> would appear to contain C<("Gold\n",
1785 "Frankincense\n", "Myrrh\n")>, or (on Win32 systems) C<("Gold\r\n",
1786 "Frankincense\r\n", "Myrrh\r\n")>.
1790 Normally, the specified file will be opened for read and write access,
1791 and will be created if it does not exist. (That is, the flags
1792 C<O_RDWR | O_CREAT> are supplied in the C<open> call.) If you want to
1793 change this, you may supply alternative flags in the C<mode> option.
1794 See L<Fcntl> for a listing of available flags.
1797 # open the file if it exists, but fail if it does not exist
1799 tie @array, 'Tie::File', $file, mode => O_RDWR;
1801 # create the file if it does not exist
1802 use Fcntl 'O_RDWR', 'O_CREAT';
1803 tie @array, 'Tie::File', $file, mode => O_RDWR | O_CREAT;
1805 # open an existing file in read-only mode
1806 use Fcntl 'O_RDONLY';
1807 tie @array, 'Tie::File', $file, mode => O_RDONLY;
1809 Opening the data file in write-only or append mode is not supported.
1813 This is an upper limit on the amount of memory that C<Tie::File> will
1814 consume at any time while managing the file. This is used for two
1815 things: managing the I<read cache> and managing the I<deferred write
1818 Records read in from the file are cached, to avoid having to re-read
1819 them repeatedly. If you read the same record twice, the first time it
1820 will be stored in memory, and the second time it will be fetched from
1821 the I<read cache>. The amount of data in the read cache will not
1822 exceed the value you specified for C<memory>. If C<Tie::File> wants
1823 to cache a new record, but the read cache is full, it will make room
1824 by expiring the least-recently visited records from the read cache.
1826 The default memory limit is 2Mib. You can adjust the maximum read
1827 cache size by supplying the C<memory> option. The argument is the
1828 desired cache size, in bytes.
1830 # I have a lot of memory, so use a large cache to speed up access
1831 tie @array, 'Tie::File', $file, memory => 20_000_000;
1833 Setting the memory limit to 0 will inhibit caching; records will be
1834 fetched from disk every time you examine them.
1836 The C<memory> value is not an absolute or exact limit on the memory
1837 used. C<Tie::File> objects contains some structures besides the read
1838 cache and the deferred write buffer, whose sizes are not charged
1843 (This is an advanced feature. Skip this section on first reading.)
1845 If you use deferred writing (See L<"Deferred Writing">, below) then
1846 data you write into the array will not be written directly to the
1847 file; instead, it will be saved in the I<deferred write buffer> to be
1848 written out later. Data in the deferred write buffer is also charged
1849 against the memory limit you set with the C<memory> option.
1851 You may set the C<dw_size> option to limit the amount of data that can
1852 be saved in the deferred write buffer. This limit may not exceed the
1853 total memory limit. For example, if you set C<dw_size> to 1000 and
1854 C<memory> to 2500, that means that no more than 1000 bytes of deferred
1855 writes will be saved up. The space available for the read cache will
1856 vary, but it will always be at least 1500 bytes (if the deferred write
1857 buffer is full) and it could grow as large as 2500 bytes (if the
1858 deferred write buffer is empty.)
1860 If you don't specify a C<dw_size>, it defaults to the entire memory
1863 =head2 Option Format
1865 C<-mode> is a synonym for C<mode>. C<-recsep> is a synonym for
1866 C<recsep>. C<-memory> is a synonym for C<memory>. You get the
1869 =head1 Public Methods
1871 The C<tie> call returns an object, say C<$o>. You may call
1873 $rec = $o->FETCH($n);
1874 $o->STORE($n, $rec);
1876 to fetch or store the record at line C<$n>, respectively; similarly
1877 the other tied array methods. (See L<perltie> for details.) You may
1878 also call the following methods on this object:
1884 will lock the tied file. C<MODE> has the same meaning as the second
1885 argument to the Perl built-in C<flock> function; for example
1886 C<LOCK_SH> or C<LOCK_EX | LOCK_NB>. (These constants are provided by
1887 the C<use Fcntl ':flock'> declaration.)
1889 C<MODE> is optional; the default is C<LOCK_EX>.
1891 C<Tie::File> promises that the following sequence of operations will
1894 my $o = tie @array, "Tie::File", $filename;
1897 In particular, C<Tie::File> will I<not> read or write the file during
1898 the C<tie> call. (Exception: Using C<mode =E<gt> O_TRUNC> will, of
1899 course, erase the file during the C<tie> call. If you want to do this
1900 safely, then open the file without C<O_TRUNC>, lock the file, and use
1903 The best way to unlock a file is to discard the object and untie the
1904 array. It is probably unsafe to unlock the file without also untying
1905 it, because if you do, changes may remain unwritten inside the object.
1906 That is why there is no shortcut for unlocking. If you really want to
1907 unlock the file prematurely, you know what to do; if you don't know
1908 what to do, then don't do it.
1910 All the usual warnings about file locking apply here. In particular,
1911 note that file locking in Perl is B<advisory>, which means that
1912 holding a lock will not prevent anyone else from reading, writing, or
1913 erasing the file; it only prevents them from getting another lock at
1914 the same time. Locks are analogous to green traffic lights: If you
1915 have a green light, that does not prevent the idiot coming the other
1916 way from plowing into you sideways; it merely guarantees to you that
1917 the idiot does not also have a green light at the same time.
1921 my $old_value = $o->autochomp(0); # disable autochomp option
1922 my $old_value = $o->autochomp(1); # enable autochomp option
1924 my $ac = $o->autochomp(); # recover current value
1926 See L<"autochomp">, above.
1928 =head2 C<defer>, C<flush>, C<discard>, and C<autodefer>
1930 See L<"Deferred Writing">, below.
1932 =head1 Tying to an already-opened filehandle
1934 If C<$fh> is a filehandle, such as is returned by C<IO::File> or one
1935 of the other C<IO> modules, you may use:
1937 tie @array, 'Tie::File', $fh, ...;
1939 Similarly if you opened that handle C<FH> with regular C<open> or
1940 C<sysopen>, you may use:
1942 tie @array, 'Tie::File', \*FH, ...;
1944 Handles that were opened write-only won't work. Handles that were
1945 opened read-only will work as long as you don't try to modify the
1946 array. Handles must be attached to seekable sources of data---that
1947 means no pipes or sockets. If C<Tie::File> can detect that you
1948 supplied a non-seekable handle, the C<tie> call will throw an
1949 exception. (On Unix systems, it can detect this.)
1951 =head1 Deferred Writing
1953 (This is an advanced feature. Skip this section on first reading.)
1955 Normally, modifying a C<Tie::File> array writes to the underlying file
1956 immediately. Every assignment like C<$a[3] = ...> rewrites as much of
1957 the file as is necessary; typically, everything from line 3 through
1958 the end will need to be rewritten. This is the simplest and most
1959 transparent behavior. Performance even for large files is reasonably
1962 However, under some circumstances, this behavior may be excessively
1963 slow. For example, suppose you have a million-record file, and you
1970 The first time through the loop, you will rewrite the entire file,
1971 from line 0 through the end. The second time through the loop, you
1972 will rewrite the entire file from line 1 through the end. The third
1973 time through the loop, you will rewrite the entire file from line 2 to
1976 If the performance in such cases is unacceptable, you may defer the
1977 actual writing, and then have it done all at once. The following loop
1978 will perform much better for large files:
1986 If C<Tie::File>'s memory limit is large enough, all the writing will
1987 done in memory. Then, when you call C<-E<gt>flush>, the entire file
1988 will be rewritten in a single pass.
1990 (Actually, the preceding discussion is something of a fib. You don't
1991 need to enable deferred writing to get good performance for this
1992 common case, because C<Tie::File> will do it for you automatically
1993 unless you specifically tell it not to. See L<"autodeferring">,
1996 Calling C<-E<gt>flush> returns the array to immediate-write mode. If
1997 you wish to discard the deferred writes, you may call C<-E<gt>discard>
1998 instead of C<-E<gt>flush>. Note that in some cases, some of the data
1999 will have been written already, and it will be too late for
2000 C<-E<gt>discard> to discard all the changes. Support for
2001 C<-E<gt>discard> may be withdrawn in a future version of C<Tie::File>.
2003 Deferred writes are cached in memory up to the limit specified by the
2004 C<dw_size> option (see above). If the deferred-write buffer is full
2005 and you try to write still more deferred data, the buffer will be
2006 flushed. All buffered data will be written immediately, the buffer
2007 will be emptied, and the now-empty space will be used for future
2010 If the deferred-write buffer isn't yet full, but the total size of the
2011 buffer and the read cache would exceed the C<memory> limit, the oldest
2012 records will be expired from the read cache until the total size is
2015 C<push>, C<pop>, C<shift>, C<unshift>, and C<splice> cannot be
2016 deferred. When you perform one of these operations, any deferred data
2017 is written to the file and the operation is performed immediately.
2018 This may change in a future version.
2020 If you resize the array with deferred writing enabled, the file will
2021 be resized immediately, but deferred records will not be written.
2022 This has a surprising consequence: C<@a = (...)> erases the file
2023 immediately, but the writing of the actual data is deferred. This
2024 might be a bug. If it is a bug, it will be fixed in a future version.
2026 =head2 Autodeferring
2028 C<Tie::File> tries to guess when deferred writing might be helpful,
2029 and to turn it on and off automatically.
2035 In this example, only the first two assignments will be done
2036 immediately; after this, all the changes to the file will be deferred
2037 up to the user-specified memory limit.
2039 You should usually be able to ignore this and just use the module
2040 without thinking about deferring. However, special applications may
2041 require fine control over which writes are deferred, or may require
2042 that all writes be immediate. To disable the autodeferment feature,
2045 (tied @o)->autodefer(0);
2049 tie @array, 'Tie::File', $file, autodefer => 0;
2052 Similarly, C<-E<gt>autodefer(1)> re-enables autodeferment, and
2053 C<-E<gt>autodefer()> recovers the current value of the autodefer setting.
2057 (That's Latin for 'warnings'.)
2063 This is BETA RELEASE SOFTWARE. It may have bugs. See the discussion
2064 below about the (lack of any) warranty.
2066 In particular, this means that the interface may change in
2067 incompatible ways from one version to the next, without warning. That
2068 has happened at least once already. The interface will freeze before
2069 Perl 5.8 is released, probably sometime in April 2002.
2073 Reasonable effort was made to make this module efficient. Nevertheless,
2074 changing the size of a record in the middle of a large file will
2075 always be fairly slow, because everything after the new record must be
2080 The behavior of tied arrays is not precisely the same as for regular
2081 arrays. For example:
2083 # This DOES print "How unusual!"
2084 undef $a[10]; print "How unusual!\n" if defined $a[10];
2086 C<undef>-ing a C<Tie::File> array element just blanks out the
2087 corresponding record in the file. When you read it back again, you'll
2088 get the empty string, so the supposedly-C<undef>'ed value will be
2089 defined. Similarly, if you have C<autochomp> disabled, then
2091 # This DOES print "How unusual!" if 'autochomp' is disabled
2093 print "How unusual!\n" if $a[10];
2095 Because when C<autochomp> is disabled, C<$a[10]> will read back as
2096 C<"\n"> (or whatever the record separator string is.)
2098 There are other minor differences, particularly regarding C<exists>
2099 and C<delete>, but in general, the correspondence is extremely close.
2103 Not quite every effort was made to make this module as efficient as
2104 possible. C<FETCHSIZE> should use binary search instead of linear
2107 The performance of the C<flush> method could be improved. At present,
2108 it still rewrites the tail of the file once for each block of
2109 contiguous lines to be changed. In the typical case, this will result
2110 in only one rewrite, but in peculiar cases it might be bad. It should
2111 be possible to perform I<all> deferred writing with a single rewrite.
2113 Profiling suggests that these defects are probably minor; in any
2114 event, they will be fixed in a future version of the module.
2118 I have supposed that since this module is concerned with file I/O,
2119 almost all normal use of it will be heavily I/O bound. This means
2120 that the time to maintain complicated data structures inside the
2121 module will be dominated by the time to actually perform the I/O.
2122 When there was an opportunity to spend CPU time to avoid doing I/O, I
2127 You might be tempted to think that deferred writing is like
2128 transactions, with C<flush> as C<commit> and C<discard> as
2129 C<rollback>, but it isn't, so don't.
2135 This version promises absolutely nothing about the internals, which
2136 may change without notice. A future version of the module will have a
2137 well-defined and stable subclassing API.
2139 =head1 WHAT ABOUT C<DB_File>?
2141 People sometimes point out that L<DB_File> will do something similar,
2142 and ask why C<Tie::File> module is necessary.
2144 There are a number of reasons that you might prefer C<Tie::File>.
2145 A list is available at C<http://perl.plover.com/TieFile/why-not-DB_File>.
2151 To contact the author, send email to: C<mjd-perl-tiefile+@plover.com>
2153 To receive an announcement whenever a new version of this module is
2154 released, send a blank email message to
2155 C<mjd-perl-tiefile-subscribe@plover.com>.
2157 The most recent version of this module, including documentation and
2158 any news of importance, will be available at
2160 http://perl.plover.com/TieFile/
2165 C<Tie::File> version 0.93 is copyright (C) 2002 Mark Jason Dominus.
2167 This library is free software; you may redistribute it and/or modify
2168 it under the same terms as Perl itself.
2170 These terms are your choice of any of (1) the Perl Artistic Licence,
2171 or (2) version 2 of the GNU General Public License as published by the
2172 Free Software Foundation, or (3) any later version of the GNU General
2175 This library is distributed in the hope that it will be useful,
2176 but WITHOUT ANY WARRANTY; without even the implied warranty of
2177 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2178 GNU General Public License for more details.
2180 You should have received a copy of the GNU General Public License
2181 along with this library program; it should be in the file C<COPYING>.
2182 If not, write to the Free Software Foundation, Inc., 59 Temple Place,
2183 Suite 330, Boston, MA 02111 USA
2185 For licensing inquiries, contact the author at:
2189 Philadelphia, PA 19107
2193 C<Tie::File> version 0.93 comes with ABSOLUTELY NO WARRANTY.
2194 For details, see the license.
2198 Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the
2199 core when I hadn't written it yet, and for generally being helpful,
2200 supportive, and competent. (Usually the rule is "choose any one.")
2201 Also big thanks to Abhijit Menon-Sen for all of the same things.
2203 Special thanks to Craig Berry and Peter Prymmer (for VMS portability
2204 help), Randy Kobes (for Win32 portability help), Clinton Pierce and
2205 Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond
2206 the call of duty), Michael G Schwern (for testing advice), and the
2207 rest of the CPAN testers (for testing generally).
2209 Additional thanks to:
2214 Tassilo von Parseval /
2219 Autrijus Tang (again) /
2225 More tests. (The cache and heap modules need more unit tests.)
2227 Improve SPLICE algorithm to use deferred writing machinery.
2229 Cleverer strategy for flushing deferred writes.
2231 More tests. (Stuff I didn't think of yet.)
2235 Fixed-length mode. Leave-blanks mode.
2237 Maybe an autolocking mode?
2239 Record locking with fcntl()? Then the module might support an undo
2240 log and get real transactions. What a tour de force that would be.