6 use Fcntl 'O_CREAT', 'O_RDWR', 'LOCK_EX', 'O_ACCMODE', 'O_RDONLY';
9 my $DEFAULT_MEMORY_SIZE = 1<<21; # 2 megabytes
10 my $DEFAULT_AUTODEFER_THRESHHOLD = 3; # 3 records
11 my $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD = 65536; # 16 disk blocksful
13 my %good_opt = map {$_ => 1, "-$_" => 1}
14 qw(memory dw_size mode recsep discipline autodefer autochomp);
18 croak "usage: tie \@array, $_[0], filename, [option => value]...";
20 my ($pack, $file, %opts) = @_;
22 # transform '-foo' keys into 'foo' keys
23 for my $key (keys %opts) {
24 unless ($good_opt{$key}) {
25 croak("$pack: Unrecognized option '$key'\n");
28 if ($key =~ s/^-+//) {
29 $opts{$key} = delete $opts{$okey};
33 unless (defined $opts{memory}) {
34 # default is the larger of the default cache size and the
35 # deferred-write buffer size (if specified)
36 $opts{memory} = $DEFAULT_MEMORY_SIZE;
37 $opts{memory} = $opts{dw_size}
38 if defined $opts{dw_size} && $opts{dw_size} > $DEFAULT_MEMORY_SIZE;
41 $opts{dw_size} = $opts{memory} unless defined $opts{dw_size};
42 if ($opts{dw_size} > $opts{memory}) {
43 croak("$pack: dw_size may not be larger than total memory allocation\n");
45 # are we in deferred-write mode?
46 $opts{defer} = 0 unless defined $opts{defer};
47 $opts{deferred} = {}; # no records are presently deferred
48 $opts{deferred_s} = 0; # count of total bytes in ->{deferred}
49 $opts{deferred_max} = -1; # empty
51 # the cache is a hash instead of an array because it is likely to be
53 $opts{cache} = Tie::File::Cache->new($opts{memory});
55 # autodeferment is enabled by default
56 $opts{autodefer} = 1 unless defined $opts{autodefer};
57 $opts{autodeferring} = 0; # but is not initially active
58 $opts{ad_history} = [];
59 $opts{autodefer_threshhold} = $DEFAULT_AUTODEFER_THRESHHOLD
60 unless defined $opts{autodefer_threshhold};
61 $opts{autodefer_filelen_threshhold} = $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD
62 unless defined $opts{autodefer_filelen_threshhold};
65 $opts{filename} = $file;
66 unless (defined $opts{recsep}) {
67 $opts{recsep} = _default_recsep();
69 $opts{recseplen} = length($opts{recsep});
70 if ($opts{recseplen} == 0) {
71 croak "Empty record separator not supported by $pack";
74 $opts{autochomp} = 1 unless defined $opts{autochomp};
76 $opts{mode} = O_CREAT|O_RDWR unless defined $opts{mode};
77 $opts{rdonly} = (($opts{mode} & O_ACCMODE) == O_RDONLY);
81 if (UNIVERSAL::isa($file, 'GLOB')) {
82 # We use 1 here on the theory that some systems
83 # may not indicate failure if we use 0.
84 # MSWin32 does not indicate failure with 0, but I don't know if
85 # it will indicate failure with 1 or not.
86 unless (seek $file, 1, SEEK_SET) {
87 croak "$pack: your filehandle does not appear to be seekable";
89 seek $file, 0, SEEK_SET # put it back
90 $fh = $file; # setting binmode is the user's problem
92 croak "usage: tie \@array, $pack, filename, [option => value]...";
94 $fh = \do { local *FH }; # only works in 5.005 and later
95 sysopen $fh, $file, $opts{mode}, 0666 or return;
98 { my $ofh = select $fh; $| = 1; select $ofh } # autoflush on write
99 if (defined $opts{discipline} && $] >= 5.006) {
100 # This avoids a compile-time warning under 5.005
101 eval 'binmode($fh, $opts{discipline})';
102 croak $@ if $@ =~ /unknown discipline/i;
107 bless \%opts => $pack;
114 # check the defer buffer
115 if ($self->_is_deferring && exists $self->{deferred}{$n}) {
116 $rec = $self->{deferred}{$n};
118 $rec = $self->_fetch($n);
121 $self->_chomp1($rec);
124 # Chomp many records in-place; return nothing useful
127 return unless $self->{autochomp};
128 if ($self->{autochomp}) {
131 substr($_, - $self->{recseplen}) = "";
136 # Chomp one record in-place; return modified record
138 my ($self, $rec) = @_;
139 return $rec unless $self->{autochomp};
140 return unless defined $rec;
141 substr($rec, - $self->{recseplen}) = "";
148 # check the record cache
149 { my $cached = $self->{cache}->lookup($n);
150 return $cached if defined $cached;
153 if ($#{$self->{offsets}} < $n) {
154 return if $self->{eof};
155 my $o = $self->_fill_offsets_to($n);
156 # If it's still undefined, there is no such record, so return 'undef'
157 return unless defined $o;
160 my $fh = $self->{FH};
161 $self->_seek($n); # we can do this now that offsets is populated
162 my $rec = $self->_read_record;
164 # If we happen to have just read the first record, check to see if
165 # the length of the record matches what 'tell' says. If not, Tie::File
166 # won't work, and should drop dead.
168 # if ($n == 0 && defined($rec) && tell($self->{fh}) != length($rec)) {
169 # if (defined $self->{discipline}) {
170 # croak "I/O discipline $self->{discipline} not supported";
172 # croak "File encoding not supported";
176 $self->{cache}->insert($n, $rec) if defined $rec && not $self->{flushing};
181 my ($self, $n, $rec) = @_;
182 die "STORE called from _check_integrity!" if $DIAGNOSTIC;
184 $self->_fixrecs($rec);
186 if ($self->{autodefer}) {
187 $self->_annotate_ad_history($n);
190 return $self->_store_deferred($n, $rec) if $self->_is_deferring;
193 # We need this to decide whether the new record will fit
194 # It incidentally populates the offsets table
195 # Note we have to do this before we alter the cache
196 # 20020324 Wait, but this DOES alter the cache. TODO BUG?
197 my $oldrec = $self->_fetch($n);
199 if (defined($self->{cache}->lookup($n))) {
200 $self->{cache}->update($n, $rec);
203 if (not defined $oldrec) {
204 # We're storing a record beyond the end of the file
205 $self->_extend_file_to($n+1);
206 $oldrec = $self->{recsep};
208 my $len_diff = length($rec) - length($oldrec);
210 # length($oldrec) here is not consistent with text mode TODO XXX BUG
211 $self->_twrite($rec, $self->{offsets}[$n], length($oldrec));
213 # now update the offsets
214 # array slice goes from element $n+1 (the first one to move)
216 for (@{$self->{offsets}}[$n+1 .. $#{$self->{offsets}}]) {
221 sub _store_deferred {
222 my ($self, $n, $rec) = @_;
223 $self->{cache}->remove($n);
224 my $old_deferred = $self->{deferred}{$n};
226 if (defined $self->{deferred_max} && $n > $self->{deferred_max}) {
227 $self->{deferred_max} = $n;
229 $self->{deferred}{$n} = $rec;
231 my $len_diff = length($rec);
232 $len_diff -= length($old_deferred) if defined $old_deferred;
233 $self->{deferred_s} += $len_diff;
234 $self->{cache}->adj_limit(-$len_diff);
235 if ($self->{deferred_s} > $self->{dw_size}) {
237 } elsif ($self->_cache_too_full) {
242 # Remove a single record from the deferred-write buffer without writing it
243 # The record need not be present
244 sub _delete_deferred {
246 my $rec = delete $self->{deferred}{$n};
247 return unless defined $rec;
249 if (defined $self->{deferred_max}
250 && $n == $self->{deferred_max}) {
251 undef $self->{deferred_max};
254 $self->{deferred_s} -= length $rec;
255 $self->{cache}->adj_limit(length $rec);
260 my $n = $#{$self->{offsets}};
261 # 20020317 Change this to binary search
262 unless ($self->{eof}) {
263 while (defined ($self->_fill_offsets_to($n+1))) {
267 my $top_deferred = $self->_defer_max;
268 $n = $top_deferred+1 if defined $top_deferred && $n < $top_deferred+1;
273 my ($self, $len) = @_;
275 if ($self->{autodefer}) {
276 $self->_annotate_ad_history('STORESIZE');
279 my $olen = $self->FETCHSIZE;
280 return if $len == $olen; # Woo-hoo!
284 if ($self->_is_deferring) {
285 for ($olen .. $len-1) {
286 $self->_store_deferred($_, $self->{recsep});
289 $self->_extend_file_to($len);
295 if ($self->_is_deferring) {
296 # TODO maybe replace this with map-plus-assignment?
297 for (grep $_ >= $len, keys %{$self->{deferred}}) {
298 $self->_delete_deferred($_);
300 $self->{deferred_max} = $len-1;
305 $#{$self->{offsets}} = $len;
306 # $self->{offsets}[0] = 0; # in case we just chopped this
308 $self->{cache}->remove(grep $_ >= $len, $self->{cache}->keys);
313 $self->SPLICE($self->FETCHSIZE, scalar(@_), @_);
314 # $self->FETCHSIZE; # av.c takes care of this for me
319 my $size = $self->FETCHSIZE;
320 return if $size == 0;
321 # print STDERR "# POPPITY POP POP POP\n";
322 scalar $self->SPLICE($size-1, 1);
327 scalar $self->SPLICE(0, 1);
332 $self->SPLICE(0, 0, @_);
333 # $self->FETCHSIZE; # av.c takes care of this for me
339 if ($self->{autodefer}) {
340 $self->_annotate_ad_history('CLEAR');
345 $self->{cache}->set_limit($self->{memory});
346 $self->{cache}->empty;
347 @{$self->{offsets}} = (0);
348 %{$self->{deferred}}= ();
349 $self->{deferred_s} = 0;
350 $self->{deferred_max} = -1;
356 # No need to pre-extend anything in this case
357 return if $self->_is_deferring;
359 $self->_fill_offsets_to($n);
360 $self->_extend_file_to($n);
366 if ($self->{autodefer}) {
367 $self->_annotate_ad_history('DELETE');
370 my $lastrec = $self->FETCHSIZE-1;
371 my $rec = $self->FETCH($n);
372 $self->_delete_deferred($n) if $self->_is_deferring;
373 if ($n == $lastrec) {
376 $#{$self->{offsets}}--;
377 $self->{cache}->remove($n);
378 # perhaps in this case I should also remove trailing null records?
380 # Note that delete @a[-3..-1] deletes the records in the wrong order,
381 # so we only chop the very last one out of the file. We could repair this
382 # by tracking deleted records inside the object.
383 } elsif ($n < $lastrec) {
384 $self->STORE($n, "");
391 return 1 if exists $self->{deferred}{$n};
392 $self->_fill_offsets_to($n); # I think this is unnecessary
393 $n < $self->FETCHSIZE;
399 if ($self->{autodefer}) {
400 $self->_annotate_ad_history('SPLICE');
403 $self->_flush if $self->_is_deferring; # move this up?
405 $self->_chomp(my @a = $self->_splice(@_));
408 $self->_chomp1(scalar $self->_splice(@_));
414 $self->flush if $self->_is_deferring;
415 $self->{cache}->delink if defined $self->{cache}; # break circular link
419 my ($self, $pos, $nrecs, @data) = @_;
422 $pos = 0 unless defined $pos;
424 # Deal with negative and other out-of-range positions
425 # Also set default for $nrecs
427 my $oldsize = $self->FETCHSIZE;
428 $nrecs = $oldsize unless defined $nrecs;
434 croak "Modification of non-creatable array value attempted, subscript $oldpos";
438 if ($pos > $oldsize) {
440 $pos = $oldsize; # This is what perl does for normal arrays
444 $self->_fixrecs(@data);
445 my $data = join '', @data;
446 my $datalen = length $data;
449 # compute length of data being removed
450 for ($pos .. $pos+$nrecs-1) {
451 last unless defined $self->_fill_offsets_to($_);
452 my $rec = $self->_fetch($_);
453 last unless defined $rec;
456 # Why don't we just use length($rec) here?
457 # Because that record might have come from the cache. _splice
458 # might have been called to flush out the deferred-write records,
459 # and in this case length($rec) is the length of the record to be
460 # *written*, not the length of the actual record in the file. But
461 # the offsets are still true. 20020322
462 $oldlen += $self->{offsets}[$_+1] - $self->{offsets}[$_]
463 if defined $self->{offsets}[$_+1];
467 $self->_twrite($data, $self->{offsets}[$pos], $oldlen);
469 # update the offsets table part 1
470 # compute the offsets of the new records:
473 push @new_offsets, $self->{offsets}[$pos];
474 for (0 .. $#data-1) {
475 push @new_offsets, $new_offsets[-1] + length($data[$_]);
479 # If we're about to splice out the end of the offsets table...
480 if ($pos + $nrecs >= @{$self->{offsets}}) {
481 $self->{eof} = 0; # ... the table is no longer complete
483 splice(@{$self->{offsets}}, $pos, $nrecs, @new_offsets);
485 # update the offsets table part 2
486 # adjust the offsets of the following old records
487 for ($pos+@data .. $#{$self->{offsets}}) {
488 $self->{offsets}[$_] += $datalen - $oldlen;
490 # If we scrubbed out all known offsets, regenerate the trivial table
491 # that knows that the file does indeed start at 0.
492 $self->{offsets}[0] = 0 unless @{$self->{offsets}};
493 # If the file got longer, the offsets table is no longer complete
494 $self->{eof} = 0 if @data > $nrecs;
497 # Perhaps the following cache foolery could be factored out
498 # into a bunch of mor opaque cache functions. For example,
499 # it's odd to delete a record from the cache and then remove
500 # it from the LRU queue later on; there should be a function to
503 # update the read cache, part 1
505 for ($pos .. $pos+$nrecs-1) {
506 my $new = $data[$_-$pos];
508 $self->{cache}->update($_, $new);
510 $self->{cache}->remove($_);
514 # update the read cache, part 2
515 # moved records - records past the site of the change
516 # need to be renumbered
517 # Maybe merge this with the previous block?
519 my @oldkeys = grep $_ >= $pos + $nrecs, $self->{cache}->keys;
520 my @newkeys = map $_-$nrecs+@data, @oldkeys;
521 $self->{cache}->rekey(\@oldkeys, \@newkeys);
524 # Now there might be too much data in the cache, if we spliced out
525 # some short records and spliced in some long ones. If so, flush
529 # Yes, the return value of 'splice' *is* actually this complicated
530 wantarray ? @result : @result ? $result[-1] : undef;
533 # write data into the file
534 # $data is the data to be written.
535 # it should be written at position $pos, and should overwrite
536 # exactly $len of the following bytes.
537 # Note that if length($data) > $len, the subsequent bytes will have to
538 # be moved up, and if length($data) < $len, they will have to
541 my ($self, $data, $pos, $len) = @_;
543 unless (defined $pos) {
544 die "\$pos was undefined in _twrite";
547 my $len_diff = length($data) - $len;
549 if ($len_diff == 0) { # Woo-hoo!
550 my $fh = $self->{fh};
552 $self->_write_record($data);
553 return; # well, that was easy.
556 # the two records are of different lengths
557 # our strategy here: rewrite the tail of the file,
558 # reading ahead one buffer at a time
559 # $bufsize is required to be at least as large as the data we're overwriting
560 my $bufsize = _bufsize($len_diff);
561 my ($writepos, $readpos) = ($pos, $pos+$len);
565 # Seems like there ought to be a way to avoid the repeated code
566 # and the special case here. The read(1) is also a little weird.
569 $self->_seekb($readpos);
570 my $br = read $self->{fh}, $next_block, $bufsize;
571 $more_data = read $self->{fh}, my($dummy), 1;
572 $self->_seekb($writepos);
573 $self->_write_record($data);
575 $writepos += length $data;
577 } while $more_data; # BUG XXX TODO how could this have worked?
578 $self->_seekb($writepos);
579 $self->_write_record($next_block);
581 # There might be leftover data at the end of the file
582 $self->_chop_file if $len_diff < 0;
585 # If a record does not already end with the appropriate terminator
586 # string, append one.
590 $_ = "" unless defined $_;
591 $_ .= $self->{recsep}
592 unless substr($_, - $self->{recseplen}) eq $self->{recsep};
597 ################################################################
599 # Basic read, write, and seek
602 # seek to the beginning of record #$n
603 # Assumes that the offsets table is already correctly populated
605 # Note that $n=-1 has a special meaning here: It means the start of
606 # the last known record; this may or may not be the very last record
607 # in the file, depending on whether the offsets table is fully populated.
611 my $o = $self->{offsets}[$n];
613 or confess("logic error: undefined offset for record $n");
614 seek $self->{fh}, $o, SEEK_SET
615 or die "Couldn't seek filehandle: $!"; # "Should never happen."
620 seek $self->{fh}, $b, SEEK_SET
621 or die "Couldn't seek filehandle: $!"; # "Should never happen."
624 # populate the offsets table up to the beginning of record $n
625 # return the offset of record $n
626 sub _fill_offsets_to {
629 return $self->{offsets}[$n] if $self->{eof};
631 my $fh = $self->{fh};
632 local *OFF = $self->{offsets};
635 until ($#OFF >= $n) {
637 $self->_seek(-1); # tricky -- see comment at _seek
638 $rec = $self->_read_record;
643 return; # It turns out there is no such record
647 # we have now read all the records up to record n-1,
648 # so we can return the offset of record n
652 # assumes that $rec is already suitably terminated
654 my ($self, $rec) = @_;
655 my $fh = $self->{fh};
657 or die "Couldn't write record: $!"; # "Should never happen."
658 # $self->{_written} += length($rec);
664 { local $/ = $self->{recsep};
665 my $fh = $self->{fh};
668 return unless defined $rec;
669 if (substr($rec, -$self->{recseplen}) ne $self->{recsep}) {
670 # improperly terminated final record --- quietly fix it.
671 # my $ac = substr($rec, -$self->{recseplen});
673 unless ($self->{rdonly}) {
674 my $fh = $self->{fh};
675 print $fh $self->{recsep};
677 $rec .= $self->{recsep};
679 # $self->{_read} += length($rec) if defined $rec;
685 @{$self}{'_read', '_written'};
688 ################################################################
690 # Read cache management
694 $self->{cache}->reduce_size_to($self->{memory} - $self->{deferred_s});
697 sub _cache_too_full {
699 $self->{cache}->bytes + $self->{deferred_s} >= $self->{memory};
702 ################################################################
704 # File custodial services
708 # We have read to the end of the file and have the offsets table
709 # entirely populated. Now we need to write a new record beyond
710 # the end of the file. We prepare for this by writing
711 # empty records into the file up to the position we want
713 # assumes that the offsets table already contains the offset of record $n,
714 # if it exists, and extends to the end of the file if not.
715 sub _extend_file_to {
717 $self->_seek(-1); # position after the end of the last record
718 my $pos = $self->{offsets}[-1];
720 # the offsets table has one entry more than the total number of records
721 my $extras = $n - $#{$self->{offsets}};
723 # Todo : just use $self->{recsep} x $extras here?
724 while ($extras-- > 0) {
725 $self->_write_record($self->{recsep});
726 push @{$self->{offsets}}, tell $self->{fh};
730 # Truncate the file at the current position
733 truncate $self->{fh}, tell($self->{fh});
737 # compute the size of a buffer suitable for moving
738 # all the data in a file forward $n bytes
739 # ($n may be negative)
740 # The result should be at least $n.
743 return 8192 if $n < 0;
745 $b += 8192 if $n & 8191;
749 ################################################################
751 # Miscellaneous public methods
756 my ($self, $op) = @_;
758 my $pack = ref $self;
759 croak "Usage: $pack\->flock([OPERATION])";
761 my $fh = $self->{fh};
762 $op = LOCK_EX unless defined $op;
766 # Get/set autochomp option
770 my $old = $self->{autochomp};
771 $self->{autochomp} = shift;
778 ################################################################
780 # Matters related to deferred writing
786 $self->_stop_autodeferring;
787 @{$self->{ad_history}} = ();
791 # Flush deferred writes
793 # This could be better optimized to write the file in one pass, instead
794 # of one pass per block of records. But that will require modifications
795 # to _twrite, so I should have a good _twite test suite first.
805 my @writable = sort {$a<=>$b} (keys %{$self->{deferred}});
808 # gather all consecutive records from the front of @writable
809 my $first_rec = shift @writable;
810 my $last_rec = $first_rec+1;
811 ++$last_rec, shift @writable while @writable && $last_rec == $writable[0];
813 $self->_fill_offsets_to($last_rec);
814 $self->_extend_file_to($last_rec);
815 $self->_splice($first_rec, $last_rec-$first_rec+1,
816 @{$self->{deferred}}{$first_rec .. $last_rec});
819 $self->_discard; # clear out defered-write-cache
822 # Discard deferred writes and disable future deferred writes
829 # Discard deferred writes, but retain old deferred writing mode
832 %{$self->{deferred}} = ();
833 $self->{deferred_s} = 0;
834 $self->{deferred_max} = -1;
835 $self->{cache}->set_limit($self->{memory});
838 # Deferred writing is enabled, either explicitly ($self->{defer})
839 # or automatically ($self->{autodeferring})
842 $self->{defer} || $self->{autodeferring};
845 # The largest record number of any deferred record
848 return $self->{deferred_max} if defined $self->{deferred_max};
850 for my $key (keys %{$self->{deferred}}) {
851 $max = $key if $key > $max;
853 $self->{deferred_max} = $max;
857 ################################################################
859 # Matters related to autodeferment
862 # Get/set autodefer option
866 my $old = $self->{autodefer};
867 $self->{autodefer} = shift;
869 $self->_stop_autodeferring;
870 @{$self->{ad_history}} = ();
878 # The user is trying to store record #$n Record that in the history,
879 # and then enable (or disable) autodeferment if that seems useful.
880 # Note that it's OK for $n to be a non-number, as long as the function
881 # is prepared to deal with that. Nobody else looks at the ad_history.
883 # Now, what does the ad_history mean, and what is this function doing?
884 # Essentially, the idea is to enable autodeferring when we see that the
885 # user has made three consecutive STORE calls to three consecutive records.
886 # ("Three" is actually ->{autodefer_threshhold}.)
887 # A STORE call for record #$n inserts $n into the autodefer history,
888 # and if the history contains three consecutive records, we enable
889 # autodeferment. An ad_history of [X, Y] means that the most recent
890 # STOREs were for records X, X+1, ..., Y, in that order.
892 # Inserting a nonconsecutive number erases the history and starts over.
894 # Performing a special operation like SPLICE erases the history.
896 # There's one special case: CLEAR means that CLEAR was just called.
897 # In this case, we prime the history with [-2, -1] so that if the next
898 # write is for record 0, autodeferring goes on immediately. This is for
899 # the common special case of "@a = (...)".
901 sub _annotate_ad_history {
903 return unless $self->{autodefer}; # feature is disabled
904 return if $self->{defer}; # already in explicit defer mode
905 return unless $self->{offsets}[-1] >= $self->{autodefer_filelen_threshhold};
907 local *H = $self->{ad_history};
909 @H = (-2, -1); # prime the history with fake records
910 $self->_stop_autodeferring;
911 } elsif ($n =~ /^\d+$/) {
915 if ($H[1] == $n-1) { # another consecutive record
917 if ($H[1] - $H[0] + 1 >= $self->{autodefer_threshhold}) {
918 $self->{autodeferring} = 1;
920 } else { # nonconsecutive- erase and start over
922 $self->_stop_autodeferring;
925 } else { # SPLICE or STORESIZE or some such
927 $self->_stop_autodeferring;
931 # If autodferring was enabled, cut it out and discard the history
932 sub _stop_autodeferring {
934 if ($self->{autodeferring}) {
937 $self->{autodeferring} = 0;
940 ################################################################
943 # This is NOT a method. It is here for two reasons:
944 # 1. To factor a fairly complicated block out of the constructor
945 # 2. To provide access for the test suite, which need to be sure
946 # files are being written properly.
947 sub _default_recsep {
949 if ($^O eq 'MSWin32') { # Dos too?
950 # Windows users expect files to be terminated with \r\n
951 # But $/ is set to \n instead
952 # Note that this also transforms \n\n into \r\n\r\n.
954 $recsep =~ s/\n/\r\n/g;
959 # Utility function for _check_integrity
967 # Given a file, make sure the cache is consistent with the
968 # file contents and the internal data structures are consistent with
969 # each other. Returns true if everything checks out, false if not
971 # The $file argument is no longer used. It is retained for compatibility
972 # with the existing test suite.
973 sub _check_integrity {
974 my ($self, $file, $warn) = @_;
975 my $rsl = $self->{recseplen};
976 my $rs = $self->{recsep};
978 local *_; # local $_ does not work here
979 local $DIAGNOSTIC = 1;
981 if (not defined $rs) {
982 _ci_warn("recsep is undef!");
984 } elsif ($rs eq "") {
985 _ci_warn("recsep is empty!");
987 } elsif ($rsl != length $rs) {
989 _ci_warn("recsep <$rs> has length $ln, should be $rsl");
993 if (not defined $self->{offsets}[0]) {
994 _ci_warn("offset 0 is missing!");
996 } elsif ($self->{offsets}[0] != 0) {
997 _ci_warn("rec 0: offset <$self->{offsets}[0]> s/b 0!");
1003 local *F = $self->{fh};
1004 seek F, 0, SEEK_SET;
1010 my $cached = $self->{cache}->_produce($n);
1011 my $offset = $self->{offsets}[$.];
1013 if (defined $offset && $offset != $ao) {
1014 _ci_warn("rec $n: offset <$offset> actual <$ao>");
1017 if (defined $cached && $_ ne $cached && ! $self->{deferred}{$n}) {
1019 _ci_warn("rec $n: cached <$cached> actual <$_>");
1021 if (defined $cached && substr($cached, -$rsl) ne $rs) {
1023 _ci_warn("rec $n in the cache is missing the record separator");
1025 if (! defined $offset && $self->{eof}) {
1027 _ci_warn("The offset table was marked complete, but it is missing element $.");
1030 if (@{$self->{offsets}} > $.+1) {
1032 my $n = @{$self->{offsets}};
1033 _ci_warn("The offset table has $n items, but the file has only $.");
1036 my $deferring = $self->_is_deferring;
1037 for my $n ($self->{cache}->keys) {
1038 my $r = $self->{cache}->_produce($n);
1039 $cached += length($r);
1040 next if $n+1 <= $.; # checked this already
1041 _ci_warn("spurious caching of record $n");
1044 my $b = $self->{cache}->bytes;
1045 if ($cached != $b) {
1046 _ci_warn("cache size is $b, should be $cached");
1051 $good = 0 unless $self->{cache}->_check_integrity;
1053 # Now let's check the deferbuffer
1054 # Unless deferred writing is enabled, it should be empty
1055 if (! $self->_is_deferring && %{$self->{deferred}}) {
1056 _ci_warn("deferred writing disabled, but deferbuffer nonempty");
1060 # Any record in the deferbuffer should *not* be present in the readcache
1062 while (my ($n, $r) = each %{$self->{deferred}}) {
1063 $deferred_s += length($r);
1064 if (defined $self->{cache}->_produce($n)) {
1065 _ci_warn("record $n is in the deferbuffer *and* the readcache");
1068 if (substr($r, -$rsl) ne $rs) {
1069 _ci_warn("rec $n in the deferbuffer is missing the record separator");
1074 # Total size of deferbuffer should match internal total
1075 if ($deferred_s != $self->{deferred_s}) {
1076 _ci_warn("buffer size is $self->{deferred_s}, should be $deferred_s");
1080 # Total size of deferbuffer should not exceed the specified limit
1081 if ($deferred_s > $self->{dw_size}) {
1082 _ci_warn("buffer size is $self->{deferred_s} which exceeds the limit of $self->{dw_size}");
1086 # Total size of cached data should not exceed the specified limit
1087 if ($deferred_s + $cached > $self->{memory}) {
1088 my $total = $deferred_s + $cached;
1089 _ci_warn("total stored data size is $total which exceeds the limit of $self->{memory}");
1093 # Stuff related to autodeferment
1094 if (!$self->{autodefer} && @{$self->{ad_history}}) {
1095 _ci_warn("autodefer is disabled, but ad_history is nonempty");
1098 if ($self->{autodeferring} && $self->{defer}) {
1099 _ci_warn("both autodeferring and explicit deferring are active");
1102 if (@{$self->{ad_history}} == 0) {
1103 # That's OK, no additional tests required
1104 } elsif (@{$self->{ad_history}} == 2) {
1105 my @non_number = grep !/^-?\d+$/, @{$self->{ad_history}};
1109 $msg = "ad_history contains non-numbers (@{$self->{ad_history}})";
1113 } elsif ($self->{ad_history}[1] < $self->{ad_history}[0]) {
1114 _ci_warn("ad_history has nonsensical values @{$self->{ad_history}}");
1118 _ci_warn("ad_history has bad length <@{$self->{ad_history}}>");
1125 ################################################################
1131 package Tie::File::Cache;
1132 $Tie::File::Cache::VERSION = $Tie::File::VERSION;
1133 use Carp ':DEFAULT', 'confess';
1142 my ($pack, $max) = @_;
1144 croak "missing argument to ->new" unless defined $max;
1146 bless $self => $pack;
1147 @$self = (Tie::File::Heap->new($self), {}, $max, 0);
1152 my ($self, $n) = @_;
1157 my ($self, $n) = @_;
1161 # For internal use only
1162 # Will be called by the heap structure to notify us that a certain
1163 # piece of data has moved from one heap element to another.
1164 # $k is the hash key of the item
1165 # $n is the new index into the heap at which it is stored
1166 # If $n is undefined, the item has been removed from the heap.
1168 my ($self, $k, $n) = @_;
1170 $self->[HASH]{$k} = $n;
1172 delete $self->[HASH]{$k};
1177 my ($self, $key, $val) = @_;
1179 croak "missing argument to ->insert" unless defined $key;
1180 unless (defined $self->[MAX]) {
1181 confess "undefined max" ;
1183 confess "undefined val" unless defined $val;
1184 return if length($val) > $self->[MAX];
1185 my $oldnode = $self->[HASH]{$key};
1186 if (defined $oldnode) {
1187 my $oldval = $self->[HEAP]->set_val($oldnode, $val);
1188 $self->[BYTES] -= length($oldval);
1190 $self->[HEAP]->insert($key, $val);
1192 $self->[BYTES] += length($val);
1198 my $old_data = $self->[HEAP]->popheap;
1199 return unless defined $old_data;
1200 $self->[BYTES] -= length $old_data;
1205 my ($self, @keys) = @_;
1207 for my $key (@keys) {
1208 next unless exists $self->[HASH]{$key};
1209 my $old_data = $self->[HEAP]->remove($self->[HASH]{$key});
1210 $self->[BYTES] -= length $old_data;
1211 push @result, $old_data;
1217 my ($self, $key) = @_;
1219 croak "missing argument to ->lookup" unless defined $key;
1220 if (exists $self->[HASH]{$key}) {
1221 $self->[HEAP]->lookup($self->[HASH]{$key});
1227 # For internal use only
1229 my ($self, $key) = @_;
1230 my $loc = $self->[HASH]{$key};
1231 return unless defined $loc;
1232 $self->[HEAP][$loc][2];
1235 # For internal use only
1237 my ($self, $key) = @_;
1238 $self->[HEAP]->promote($self->[HASH]{$key});
1243 %{$self->[HASH]} = ();
1245 $self->[HEAP]->empty;
1250 keys %{$self->[HASH]} == 0;
1254 my ($self, $key, $val) = @_;
1256 croak "missing argument to ->update" unless defined $key;
1257 if (length($val) > $self->[MAX]) {
1258 my $oldval = $self->remove($key);
1259 $self->[BYTES] -= length($oldval) if defined $oldval;
1260 } elsif (exists $self->[HASH]{$key}) {
1261 my $oldval = $self->[HEAP]->set_val($self->[HASH]{$key}, $val);
1262 $self->[BYTES] += length($val);
1263 $self->[BYTES] -= length($oldval) if defined $oldval;
1265 $self->[HEAP]->insert($key, $val);
1266 $self->[BYTES] += length($val);
1272 my ($self, $okeys, $nkeys) = @_;
1275 @map{@$okeys} = @$nkeys;
1276 croak "missing argument to ->rekey" unless defined $nkeys;
1277 croak "length mismatch in ->rekey arguments" unless @$nkeys == @$okeys;
1278 my %adjusted; # map new keys to heap indices
1279 # You should be able to cut this to one loop TODO XXX
1280 for (0 .. $#$okeys) {
1281 $adjusted{$nkeys->[$_]} = delete $self->[HASH]{$okeys->[$_]};
1283 while (my ($nk, $ix) = each %adjusted) {
1284 # @{$self->[HASH]}{keys %adjusted} = values %adjusted;
1285 $self->[HEAP]->rekey($ix, $nk);
1286 $self->[HASH]{$nk} = $ix;
1292 my @a = keys %{$self->[HASH]};
1301 sub reduce_size_to {
1302 my ($self, $max) = @_;
1303 until ($self->is_empty || $self->[BYTES] <= $max) {
1310 until ($self->is_empty || $self->[BYTES] <= $self->[MAX]) {
1315 # For internal use only
1318 $self->[HEAP]->expire_order;
1321 sub _check_integrity {
1323 $self->[HEAP]->_check_integrity;
1328 $self->[HEAP] = undef; # Bye bye heap
1331 ################################################################
1335 # Heap data structure for use by cache LRU routines
1337 package Tie::File::Heap;
1338 use Carp ':DEFAULT', 'confess';
1339 $Tie::File::Heap::VERSION = $Tie::File::Cache::VERSION;
1345 my ($pack, $cache) = @_;
1346 die "$pack: Parent cache object $cache does not support _heap_move method"
1347 unless eval { $cache->can('_heap_move') };
1348 my $self = [[0,$cache,0]];
1349 bless $self => $pack;
1352 # Allocate a new sequence number, larger than all previously allocated numbers
1387 $self->[0][0] = 0; # might as well reset the sequence numbers
1390 # notify the parent cache object that we moved something
1393 $self->_cache->_heap_move(@_);
1396 # Insert a piece of data into the heap with the indicated sequence number.
1397 # The item with the smallest sequence number is always at the top.
1398 # If no sequence number is specified, allocate a new one and insert the
1399 # item at the bottom.
1401 my ($self, $key, $data, $seq) = @_;
1402 $seq = $self->_nseq unless defined $seq;
1403 $self->_insert_new([$seq, $key, $data]);
1406 # Insert a new, fresh item at the bottom of the heap
1408 my ($self, $item) = @_;
1410 $i = int($i/2) until defined $self->[$i/2];
1411 $self->[$i] = $item;
1412 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1416 # Insert [$data, $seq] pair at or below item $i in the heap.
1417 # If $i is omitted, default to 1 (the top element.)
1419 my ($self, $item, $i) = @_;
1420 $self->_check_loc($i) if defined $i;
1421 $i = 1 unless defined $i;
1422 until (! defined $self->[$i]) {
1423 if ($self->[$i][SEQ] > $item->[SEQ]) { # inserted item is older
1424 ($self->[$i], $item) = ($item, $self->[$i]);
1425 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1427 # If either is undefined, go that way. Otherwise, choose at random
1429 $dir = 0 if !defined $self->[2*$i];
1430 $dir = 1 if !defined $self->[2*$i+1];
1431 $dir = int(rand(2)) unless defined $dir;
1434 $self->[$i] = $item;
1435 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1439 # Remove the item at node $i from the heap, moving child items upwards.
1440 # The item with the smallest sequence number is always at the top.
1441 # Moving items upwards maintains this condition.
1442 # Return the removed item.
1444 my ($self, $i) = @_;
1445 $i = 1 unless defined $i;
1446 my $top = $self->[$i];
1447 return unless defined $top;
1450 my ($L, $R) = (2*$i, 2*$i+1);
1452 # If either is undefined, go the other way.
1453 # Otherwise, go towards the smallest.
1454 last unless defined $self->[$L] || defined $self->[$R];
1455 $ii = $R if not defined $self->[$L];
1456 $ii = $L if not defined $self->[$R];
1457 unless (defined $ii) {
1458 $ii = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
1461 $self->[$i] = $self->[$ii]; # Promote child to fill vacated spot
1462 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1463 $i = $ii; # Fill new vacated spot
1465 $self->[0][1]->_heap_move($top->[KEY], undef);
1476 # set the sequence number of the indicated item to a higher number
1477 # than any other item in the heap, and bubble the item down to the
1480 my ($self, $n) = @_;
1481 $self->_check_loc($n);
1482 $self->[$n][SEQ] = $self->_nseq;
1485 my ($L, $R) = (2*$i, 2*$i+1);
1487 last unless defined $self->[$L] || defined $self->[$R];
1488 $dir = $R unless defined $self->[$L];
1489 $dir = $L unless defined $self->[$R];
1490 unless (defined $dir) {
1491 $dir = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
1493 @{$self}[$i, $dir] = @{$self}[$dir, $i];
1495 $self->[0][1]->_heap_move($self->[$_][KEY], $_) if defined $self->[$_];
1501 # Return item $n from the heap, promoting its LRU status
1503 my ($self, $n) = @_;
1504 $self->_check_loc($n);
1505 my $val = $self->[$n];
1511 # Assign a new value for node $n, promoting it to the bottom of the heap
1513 my ($self, $n, $val) = @_;
1514 $self->_check_loc($n);
1515 my $oval = $self->[$n][DAT];
1516 $self->[$n][DAT] = $val;
1521 # The hask key has changed for an item;
1522 # alter the heap's record of the hash key
1524 my ($self, $n, $new_key) = @_;
1525 $self->_check_loc($n);
1526 $self->[$n][KEY] = $new_key;
1530 my ($self, $n) = @_;
1531 unless (defined $self->[$n]) {
1532 confess "_check_loc($n) failed";
1536 sub _check_integrity {
1539 unless (eval {$self->[0][1]->isa("Tie::File::Cache")}) {
1540 print "# Element 0 of heap corrupt\n";
1543 $good = 0 unless $self->_satisfies_heap_condition(1);
1544 for my $i (2 .. $#{$self}) {
1545 my $p = int($i/2); # index of parent node
1546 if (defined $self->[$i] && ! defined $self->[$p]) {
1547 print "# Element $i of heap defined, but parent $p isn't\n";
1554 sub _satisfies_heap_condition {
1560 next unless defined $self->[$c];
1561 if ($self->[$n][SEQ] >= $self->[$c]) {
1562 print "# Node $n of heap does not predate node $c\n";
1565 $good = 0 unless $self->_satisfies_heap_condition($c);
1570 # Return a list of all the values, sorted by expiration order
1573 my @nodes = sort {$a->[SEQ] <=> $b->[SEQ]} $self->_nodes;
1574 map { $_->[KEY] } @nodes;
1580 return unless defined $self->[$i];
1581 ($self->[$i], $self->_nodes($i*2), $self->_nodes($i*2+1));
1584 "Cogito, ergo sum."; # don't forget to return a true value from the file
1588 Tie::File - Access the lines of a disk file via a Perl array
1592 # This file documents Tie::File version 0.90
1594 tie @array, 'Tie::File', filename or die ...;
1596 $array[13] = 'blah'; # line 13 of the file is now 'blah'
1597 print $array[42]; # display line 42 of the file
1599 $n_recs = @array; # how many records are in the file?
1600 $#array -= 2; # chop two records off the end
1604 s/PERL/Perl/g; # Replace PERL with Perl everywhere in the file
1607 # These are just like regular push, pop, unshift, shift, and splice
1608 # Except that they modify the file in the way you would expect
1610 push @array, new recs...;
1611 my $r1 = pop @array;
1612 unshift @array, new recs...;
1613 my $r1 = shift @array;
1614 @old_recs = splice @array, 3, 7, new recs...;
1616 untie @array; # all finished
1621 C<Tie::File> represents a regular text file as a Perl array. Each
1622 element in the array corresponds to a record in the file. The first
1623 line of the file is element 0 of the array; the second line is element
1626 The file is I<not> loaded into memory, so this will work even for
1629 Changes to the array are reflected in the file immediately.
1631 Lazy people and beginners may now stop reading the manual.
1635 What is a 'record'? By default, the meaning is the same as for the
1636 C<E<lt>...E<gt>> operator: It's a string terminated by C<$/>, which is
1637 probably C<"\n">. (Minor exception: on dos and Win32 systems, a
1638 'record' is a string terminated by C<"\r\n">.) You may change the
1639 definition of "record" by supplying the C<recsep> option in the C<tie>
1642 tie @array, 'Tie::File', $file, recsep => 'es';
1644 This says that records are delimited by the string C<es>. If the file
1645 contained the following data:
1647 Curse these pesky flies!\n
1649 then the C<@array> would appear to have four elements:
1656 An undefined value is not permitted as a record separator. Perl's
1657 special "paragraph mode" semantics (E<agrave> la C<$/ = "">) are not
1660 Records read from the tied array do not have the record separator
1661 string on the end; this is to allow
1663 $array[17] .= "extra";
1665 to work as expected.
1667 (See L<"autochomp">, below.) Records stored into the array will have
1668 the record separator string appended before they are written to the
1669 file, if they don't have one already. For example, if the record
1670 separator string is C<"\n">, then the following two lines do exactly
1673 $array[17] = "Cherry pie";
1674 $array[17] = "Cherry pie\n";
1676 The result is that the contents of line 17 of the file will be
1677 replaced with "Cherry pie"; a newline character will separate line 17
1678 from line 18. This means that this code will do nothing:
1682 Because the C<chomp>ed value will have the separator reattached when
1683 it is written back to the file. There is no way to create a file
1684 whose trailing record separator string is missing.
1686 Inserting records that I<contain> the record separator string is not
1687 supported by this module. It will probably produce a reasonable
1688 result, but what this result will be may change in a future version.
1689 Use 'splice' to insert records or to replace one record with several.
1693 Normally, array elements have the record separator removed, so that if
1694 the file contains the text
1700 the tied array will appear to contain C<("Gold", "Frankincense",
1701 "Myrrh")>. If you set C<autochomp> to a false value, the record
1702 separator will not be removed. If the file above was tied with
1704 tie @gifts, "Tie::File", $gifts, autochomp => 0;
1706 then the array C<@gifts> would appear to contain C<("Gold\n",
1707 "Frankincense\n", "Myrrh\n")>, or (on Win32 systems) C<("Gold\r\n",
1708 "Frankincense\r\n", "Myrrh\r\n")>.
1712 Normally, the specified file will be opened for read and write access,
1713 and will be created if it does not exist. (That is, the flags
1714 C<O_RDWR | O_CREAT> are supplied in the C<open> call.) If you want to
1715 change this, you may supply alternative flags in the C<mode> option.
1716 See L<Fcntl> for a listing of available flags.
1719 # open the file if it exists, but fail if it does not exist
1721 tie @array, 'Tie::File', $file, mode => O_RDWR;
1723 # create the file if it does not exist
1724 use Fcntl 'O_RDWR', 'O_CREAT';
1725 tie @array, 'Tie::File', $file, mode => O_RDWR | O_CREAT;
1727 # open an existing file in read-only mode
1728 use Fcntl 'O_RDONLY';
1729 tie @array, 'Tie::File', $file, mode => O_RDONLY;
1731 Opening the data file in write-only or append mode is not supported.
1735 This is an upper limit on the amount of memory that C<Tie::File> will
1736 consume at any time while managing the file. This is used for two
1737 things: managing the I<read cache> and managing the I<deferred write
1740 Records read in from the file are cached, to avoid having to re-read
1741 them repeatedly. If you read the same record twice, the first time it
1742 will be stored in memory, and the second time it will be fetched from
1743 the I<read cache>. The amount of data in the read cache will not
1744 exceed the value you specified for C<memory>. If C<Tie::File> wants
1745 to cache a new record, but the read cache is full, it will make room
1746 by expiring the least-recently visited records from the read cache.
1748 The default memory limit is 2Mib. You can adjust the maximum read
1749 cache size by supplying the C<memory> option. The argument is the
1750 desired cache size, in bytes.
1752 # I have a lot of memory, so use a large cache to speed up access
1753 tie @array, 'Tie::File', $file, memory => 20_000_000;
1755 Setting the memory limit to 0 will inhibit caching; records will be
1756 fetched from disk every time you examine them.
1758 The C<memory> value is not an absolute or exact limit on the memory
1759 used. C<Tie::File> objects contains some structures besides the read
1760 cache and the deferred write buffer, whose sizes are not charged
1765 (This is an advanced feature. Skip this section on first reading.)
1767 If you use deferred writing (See L<"Deferred Writing">, below) then
1768 data you write into the array will not be written directly to the
1769 file; instead, it will be saved in the I<deferred write buffer> to be
1770 written out later. Data in the deferred write buffer is also charged
1771 against the memory limit you set with the C<memory> option.
1773 You may set the C<dw_size> option to limit the amount of data that can
1774 be saved in the deferred write buffer. This limit may not exceed the
1775 total memory limit. For example, if you set C<dw_size> to 1000 and
1776 C<memory> to 2500, that means that no more than 1000 bytes of deferred
1777 writes will be saved up. The space available for the read cache will
1778 vary, but it will always be at least 1500 bytes (if the deferred write
1779 buffer is full) and it could grow as large as 2500 bytes (if the
1780 deferred write buffer is empty.)
1782 If you don't specify a C<dw_size>, it defaults to the entire memory
1785 =head2 Option Format
1787 C<-mode> is a synonym for C<mode>. C<-recsep> is a synonym for
1788 C<recsep>. C<-memory> is a synonym for C<memory>. You get the
1791 =head1 Public Methods
1793 The C<tie> call returns an object, say C<$o>. You may call
1795 $rec = $o->FETCH($n);
1796 $o->STORE($n, $rec);
1798 to fetch or store the record at line C<$n>, respectively; similarly
1799 the other tied array methods. (See L<perltie> for details.) You may
1800 also call the following methods on this object:
1806 will lock the tied file. C<MODE> has the same meaning as the second
1807 argument to the Perl built-in C<flock> function; for example
1808 C<LOCK_SH> or C<LOCK_EX | LOCK_NB>. (These constants are provided by
1809 the C<use Fcntl ':flock'> declaration.)
1811 C<MODE> is optional; the default is C<LOCK_EX>.
1813 C<Tie::File> promises that the following sequence of operations will
1816 my $o = tie @array, "Tie::File", $filename;
1819 In particular, C<Tie::File> will I<not> read or write the file during
1820 the C<tie> call. (Exception: Using C<mode =E<gt> O_TRUNC> will, of
1821 course, erase the file during the C<tie> call. If you want to do this
1822 safely, then open the file without C<O_TRUNC>, lock the file, and use
1825 The best way to unlock a file is to discard the object and untie the
1826 array. It is probably unsafe to unlock the file without also untying
1827 it, because if you do, changes may remain unwritten inside the object.
1828 That is why there is no shortcut for unlocking. If you really want to
1829 unlock the file prematurely, you know what to do; if you don't know
1830 what to do, then don't do it.
1832 All the usual warnings about file locking apply here. In particular,
1833 note that file locking in Perl is B<advisory>, which means that
1834 holding a lock will not prevent anyone else from reading, writing, or
1835 erasing the file; it only prevents them from getting another lock at
1836 the same time. Locks are analogous to green traffic lights: If you
1837 have a green light, that does not prevent the idiot coming the other
1838 way from plowing into you sideways; it merely guarantees to you that
1839 the idiot does not also have a green light at the same time.
1843 my $old_value = $o->autochomp(0); # disable autochomp option
1844 my $old_value = $o->autochomp(1); # enable autochomp option
1846 my $ac = $o->autochomp(); # recover current value
1848 See L<"autochomp">, above.
1850 =head2 C<defer>, C<flush>, C<discard>, and C<autodefer>
1852 See L<"Deferred Writing">, below.
1854 =head1 Tying to an already-opened filehandle
1856 If C<$fh> is a filehandle, such as is returned by C<IO::File> or one
1857 of the other C<IO> modules, you may use:
1859 tie @array, 'Tie::File', $fh, ...;
1861 Similarly if you opened that handle C<FH> with regular C<open> or
1862 C<sysopen>, you may use:
1864 tie @array, 'Tie::File', \*FH, ...;
1866 Handles that were opened write-only won't work. Handles that were
1867 opened read-only will work as long as you don't try to modify the
1868 array. Handles must be attached to seekable sources of data---that
1869 means no pipes or sockets. If C<Tie::File> can detect that you
1870 supplied a non-seekable handle, the C<tie> call will throw an
1871 exception. (On Unix systems, it can detect this.)
1873 =head1 Deferred Writing
1875 (This is an advanced feature. Skip this section on first reading.)
1877 Normally, modifying a C<Tie::File> array writes to the underlying file
1878 immediately. Every assignment like C<$a[3] = ...> rewrites as much of
1879 the file as is necessary; typically, everything from line 3 through
1880 the end will need to be rewritten. This is the simplest and most
1881 transparent behavior. Performance even for large files is reasonably
1884 However, under some circumstances, this behavior may be excessively
1885 slow. For example, suppose you have a million-record file, and you
1892 The first time through the loop, you will rewrite the entire file,
1893 from line 0 through the end. The second time through the loop, you
1894 will rewrite the entire file from line 1 through the end. The third
1895 time through the loop, you will rewrite the entire file from line 2 to
1898 If the performance in such cases is unacceptable, you may defer the
1899 actual writing, and then have it done all at once. The following loop
1900 will perform much better for large files:
1908 If C<Tie::File>'s memory limit is large enough, all the writing will
1909 done in memory. Then, when you call C<-E<gt>flush>, the entire file
1910 will be rewritten in a single pass.
1912 (Actually, the preceding discussion is something of a fib. You don't
1913 need to enable deferred writing to get good performance for this
1914 common case, because C<Tie::File> will do it for you automatically
1915 unless you specifically tell it not to. See L<"autodeferring">,
1918 Calling C<-E<gt>flush> returns the array to immediate-write mode. If
1919 you wish to discard the deferred writes, you may call C<-E<gt>discard>
1920 instead of C<-E<gt>flush>. Note that in some cases, some of the data
1921 will have been written already, and it will be too late for
1922 C<-E<gt>discard> to discard all the changes. Support for
1923 C<-E<gt>discard> may be withdrawn in a future version of C<Tie::File>.
1925 Deferred writes are cached in memory up to the limit specified by the
1926 C<dw_size> option (see above). If the deferred-write buffer is full
1927 and you try to write still more deferred data, the buffer will be
1928 flushed. All buffered data will be written immediately, the buffer
1929 will be emptied, and the now-empty space will be used for future
1932 If the deferred-write buffer isn't yet full, but the total size of the
1933 buffer and the read cache would exceed the C<memory> limit, the oldest
1934 records will be expired from the read cache until the total size is
1937 C<push>, C<pop>, C<shift>, C<unshift>, and C<splice> cannot be
1938 deferred. When you perform one of these operations, any deferred data
1939 is written to the file and the operation is performed immediately.
1940 This may change in a future version.
1942 If you resize the array with deferred writing enabled, the file will
1943 be resized immediately, but deferred records will not be written.
1944 This has a surprising consequence: C<@a = (...)> erases the file
1945 immediately, but the writing of the actual data is deferred. This
1946 might be a bug. If it is a bug, it will be fixed in a future version.
1948 =head2 Autodeferring
1950 C<Tie::File> tries to guess when deferred writing might be helpful,
1951 and to turn it on and off automatically.
1957 In this example, only the first two assignments will be done
1958 immediately; after this, all the changes to the file will be deferred
1959 up to the user-specified memory limit.
1961 You should usually be able to ignore this and just use the module
1962 without thinking about deferring. However, special applications may
1963 require fine control over which writes are deferred, or may require
1964 that all writes be immediate. To disable the autodeferment feature,
1967 (tied @o)->autodefer(0);
1971 tie @array, 'Tie::File', $file, autodefer => 0;
1974 Similarly, C<-E<gt>autodefer(1)> re-enables autodeferment, and
1975 C<-E<gt>autodefer()> recovers the current value of the autodefer setting.
1979 (That's Latin for 'warnings'.)
1985 This is BETA RELEASE SOFTWARE. It may have bugs. See the discussion
1986 below about the (lack of any) warranty.
1988 In particular, this means that the interface may change in
1989 incompatible ways from one version to the next, without warning. That
1990 has happened at least once already. The interface will freeze before
1991 Perl 5.8 is released, probably sometime in April 2002.
1995 Reasonable effort was made to make this module efficient. Nevertheless,
1996 changing the size of a record in the middle of a large file will
1997 always be fairly slow, because everything after the new record must be
2002 The behavior of tied arrays is not precisely the same as for regular
2003 arrays. For example:
2005 # This DOES print "How unusual!"
2006 undef $a[10]; print "How unusual!\n" if defined $a[10];
2008 C<undef>-ing a C<Tie::File> array element just blanks out the
2009 corresponding record in the file. When you read it back again, you'll
2010 get the empty string, so the supposedly-C<undef>'ed value will be
2011 defined. Similarly, if you have C<autochomp> disabled, then
2013 # This DOES print "How unusual!" if 'autochomp' is disabled
2015 print "How unusual!\n" if $a[10];
2017 Because when C<autochomp> is disabled, C<$a[10]> will read back as
2018 C<"\n"> (or whatever the record separator string is.)
2020 There are other minor differences, particularly regarding C<exists>
2021 and C<delete>, but in general, the correspondence is extremely close.
2025 Not quite every effort was made to make this module as efficient as
2026 possible. C<FETCHSIZE> should use binary search instead of linear
2029 The performance of the C<flush> method could be improved. At present,
2030 it still rewrites the tail of the file once for each block of
2031 contiguous lines to be changed. In the typical case, this will result
2032 in only one rewrite, but in peculiar cases it might be bad. It should
2033 be possible to perform I<all> deferred writing with a single rewrite.
2035 Profiling suggests that these defects are probably minor; in any
2036 event, they will be fixed in a future version of the module.
2040 I have supposed that since this module is concerned with file I/O,
2041 almost all normal use of it will be heavily I/O bound. This means
2042 that the time to maintain complicated data structures inside the
2043 module will be dominated by the time to actually perform the I/O.
2044 When there was an opportunity to spend CPU time to avoid doing I/O, I
2049 You might be tempted to think that deferred writing is like
2050 transactions, with C<flush> as C<commit> and C<discard> as
2051 C<rollback>, but it isn't, so don't.
2057 This version promises absolutely nothing about the internals, which
2058 may change without notice. A future version of the module will have a
2059 well-defined and stable subclassing API.
2061 =head1 WHAT ABOUT C<DB_File>?
2063 People sometimes point out that L<DB_File> will do something similar,
2064 and ask why C<Tie::File> module is necessary.
2066 There are a number of reasons that you might prefer C<Tie::File>.
2067 A list is available at C<http://perl.plover.com/TieFile/why-not-DB_File>.
2073 To contact the author, send email to: C<mjd-perl-tiefile+@plover.com>
2075 To receive an announcement whenever a new version of this module is
2076 released, send a blank email message to
2077 C<mjd-perl-tiefile-subscribe@plover.com>.
2079 The most recent version of this module, including documentation and
2080 any news of importance, will be available at
2082 http://perl.plover.com/TieFile/
2087 C<Tie::File> version 0.90 is copyright (C) 2002 Mark Jason Dominus.
2089 This library is free software; you may redistribute it and/or modify
2090 it under the same terms as Perl itself.
2092 These terms are your choice of any of (1) the Perl Artistic Licence,
2093 or (2) version 2 of the GNU General Public License as published by the
2094 Free Software Foundation, or (3) any later version of the GNU General
2097 This library is distributed in the hope that it will be useful,
2098 but WITHOUT ANY WARRANTY; without even the implied warranty of
2099 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2100 GNU General Public License for more details.
2102 You should have received a copy of the GNU General Public License
2103 along with this library program; it should be in the file C<COPYING>.
2104 If not, write to the Free Software Foundation, Inc., 59 Temple Place,
2105 Suite 330, Boston, MA 02111 USA
2107 For licensing inquiries, contact the author at:
2111 Philadelphia, PA 19107
2115 C<Tie::File> version 0.90 comes with ABSOLUTELY NO WARRANTY.
2116 For details, see the license.
2120 Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the
2121 core when I hadn't written it yet, and for generally being helpful,
2122 supportive, and competent. (Usually the rule is "choose any one.")
2123 Also big thanks to Abhijit Menon-Sen for all of the same things.
2125 Special thanks to Craig Berry and Peter Prymmer (for VMS portability
2126 help), Randy Kobes (for Win32 portability help), Clinton Pierce and
2127 Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond
2128 the call of duty), Michael G Schwern (for testing advice), and the
2129 rest of the CPAN testers (for testing generally).
2131 Additional thanks to:
2136 Tassilo von Parseval /
2141 Autrijus Tang (again) /
2147 More tests. (The cache and heap modules need more unit tests.)
2149 Improve SPLICE algorithm to use deferred writing machinery.
2151 Cleverer strategy for flushing deferred writes.
2153 More tests. (Stuff I didn't think of yet.)
2157 Fixed-length mode. Leave-blanks mode.
2159 Maybe an autolocking mode?
2161 Record locking with fcntl()? Then the module might support an undo
2162 log and get real transactions. What a tour de force that would be.