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);
82 if (UNIVERSAL::isa($file, 'GLOB')) {
83 # We use 1 here on the theory that some systems
84 # may not indicate failure if we use 0.
85 # MSWin32 does not indicate failure with 0, but I don't know if
86 # it will indicate failure with 1 or not.
87 unless (seek $file, 1, SEEK_SET) {
88 croak "$pack: your filehandle does not appear to be seekable";
90 seek $file, 0, SEEK_SET # put it back
91 $fh = $file; # setting binmode is the user's problem
93 croak "usage: tie \@array, $pack, filename, [option => value]...";
95 $fh = \do { local *FH }; # only works in 5.005 and later
96 sysopen $fh, $file, $opts{mode}, 0666 or return;
99 { my $ofh = select $fh; $| = 1; select $ofh } # autoflush on write
100 if (defined $opts{discipline} && $] >= 5.006) {
101 # This avoids a compile-time warning under 5.005
102 eval 'binmode($fh, $opts{discipline})';
103 croak $@ if $@ =~ /unknown discipline/i;
108 bless \%opts => $pack;
115 # check the defer buffer
116 if ($self->_is_deferring && exists $self->{deferred}{$n}) {
117 $rec = $self->{deferred}{$n};
119 $rec = $self->_fetch($n);
122 $self->_chomp1($rec);
125 # Chomp many records in-place; return nothing useful
128 return unless $self->{autochomp};
129 if ($self->{autochomp}) {
132 substr($_, - $self->{recseplen}) = "";
137 # Chomp one record in-place; return modified record
139 my ($self, $rec) = @_;
140 return $rec unless $self->{autochomp};
141 return unless defined $rec;
142 substr($rec, - $self->{recseplen}) = "";
149 # check the record cache
150 { my $cached = $self->{cache}->lookup($n);
151 return $cached if defined $cached;
154 if ($#{$self->{offsets}} < $n) {
155 return if $self->{eof};
156 my $o = $self->_fill_offsets_to($n);
157 # If it's still undefined, there is no such record, so return 'undef'
158 return unless defined $o;
161 my $fh = $self->{FH};
162 $self->_seek($n); # we can do this now that offsets is populated
163 my $rec = $self->_read_record;
165 # If we happen to have just read the first record, check to see if
166 # the length of the record matches what 'tell' says. If not, Tie::File
167 # won't work, and should drop dead.
169 # if ($n == 0 && defined($rec) && tell($self->{fh}) != length($rec)) {
170 # if (defined $self->{discipline}) {
171 # croak "I/O discipline $self->{discipline} not supported";
173 # croak "File encoding not supported";
177 $self->{cache}->insert($n, $rec) if defined $rec && not $self->{flushing};
182 my ($self, $n, $rec) = @_;
183 die "STORE called from _check_integrity!" if $DIAGNOSTIC;
185 $self->_fixrecs($rec);
187 if ($self->{autodefer}) {
188 $self->_annotate_ad_history($n);
191 return $self->_store_deferred($n, $rec) if $self->_is_deferring;
194 # We need this to decide whether the new record will fit
195 # It incidentally populates the offsets table
196 # Note we have to do this before we alter the cache
197 # 20020324 Wait, but this DOES alter the cache. TODO BUG?
198 my $oldrec = $self->_fetch($n);
200 if (defined($self->{cache}->lookup($n))) {
201 $self->{cache}->update($n, $rec);
204 if (not defined $oldrec) {
205 # We're storing a record beyond the end of the file
206 $self->_extend_file_to($n+1);
207 $oldrec = $self->{recsep};
209 my $len_diff = length($rec) - length($oldrec);
211 # length($oldrec) here is not consistent with text mode TODO XXX BUG
212 $self->_twrite($rec, $self->{offsets}[$n], length($oldrec));
214 # now update the offsets
215 # array slice goes from element $n+1 (the first one to move)
217 for (@{$self->{offsets}}[$n+1 .. $#{$self->{offsets}}]) {
222 sub _store_deferred {
223 my ($self, $n, $rec) = @_;
224 $self->{cache}->remove($n);
225 my $old_deferred = $self->{deferred}{$n};
227 if (defined $self->{deferred_max} && $n > $self->{deferred_max}) {
228 $self->{deferred_max} = $n;
230 $self->{deferred}{$n} = $rec;
232 my $len_diff = length($rec);
233 $len_diff -= length($old_deferred) if defined $old_deferred;
234 $self->{deferred_s} += $len_diff;
235 $self->{cache}->adj_limit(-$len_diff);
236 if ($self->{deferred_s} > $self->{dw_size}) {
238 } elsif ($self->_cache_too_full) {
243 # Remove a single record from the deferred-write buffer without writing it
244 # The record need not be present
245 sub _delete_deferred {
247 my $rec = delete $self->{deferred}{$n};
248 return unless defined $rec;
250 if (defined $self->{deferred_max}
251 && $n == $self->{deferred_max}) {
252 undef $self->{deferred_max};
255 $self->{deferred_s} -= length $rec;
256 $self->{cache}->adj_limit(length $rec);
261 my $n = $#{$self->{offsets}};
262 # 20020317 Change this to binary search
263 unless ($self->{eof}) {
264 while (defined ($self->_fill_offsets_to($n+1))) {
268 my $top_deferred = $self->_defer_max;
269 $n = $top_deferred+1 if defined $top_deferred && $n < $top_deferred+1;
274 my ($self, $len) = @_;
276 if ($self->{autodefer}) {
277 $self->_annotate_ad_history('STORESIZE');
280 my $olen = $self->FETCHSIZE;
281 return if $len == $olen; # Woo-hoo!
285 if ($self->_is_deferring) {
286 for ($olen .. $len-1) {
287 $self->_store_deferred($_, $self->{recsep});
290 $self->_extend_file_to($len);
296 if ($self->_is_deferring) {
297 # TODO maybe replace this with map-plus-assignment?
298 for (grep $_ >= $len, keys %{$self->{deferred}}) {
299 $self->_delete_deferred($_);
301 $self->{deferred_max} = $len-1;
306 $#{$self->{offsets}} = $len;
307 # $self->{offsets}[0] = 0; # in case we just chopped this
309 $self->{cache}->remove(grep $_ >= $len, $self->{cache}->keys);
314 $self->SPLICE($self->FETCHSIZE, scalar(@_), @_);
315 # $self->FETCHSIZE; # av.c takes care of this for me
320 my $size = $self->FETCHSIZE;
321 return if $size == 0;
322 # print STDERR "# POPPITY POP POP POP\n";
323 scalar $self->SPLICE($size-1, 1);
328 scalar $self->SPLICE(0, 1);
333 $self->SPLICE(0, 0, @_);
334 # $self->FETCHSIZE; # av.c takes care of this for me
340 if ($self->{autodefer}) {
341 $self->_annotate_ad_history('CLEAR');
346 $self->{cache}->set_limit($self->{memory});
347 $self->{cache}->empty;
348 @{$self->{offsets}} = (0);
349 %{$self->{deferred}}= ();
350 $self->{deferred_s} = 0;
351 $self->{deferred_max} = -1;
357 # No need to pre-extend anything in this case
358 return if $self->_is_deferring;
360 $self->_fill_offsets_to($n);
361 $self->_extend_file_to($n);
367 if ($self->{autodefer}) {
368 $self->_annotate_ad_history('DELETE');
371 my $lastrec = $self->FETCHSIZE-1;
372 my $rec = $self->FETCH($n);
373 $self->_delete_deferred($n) if $self->_is_deferring;
374 if ($n == $lastrec) {
377 $#{$self->{offsets}}--;
378 $self->{cache}->remove($n);
379 # perhaps in this case I should also remove trailing null records?
381 # Note that delete @a[-3..-1] deletes the records in the wrong order,
382 # so we only chop the very last one out of the file. We could repair this
383 # by tracking deleted records inside the object.
384 } elsif ($n < $lastrec) {
385 $self->STORE($n, "");
392 return 1 if exists $self->{deferred}{$n};
393 $self->_fill_offsets_to($n); # I think this is unnecessary
394 $n < $self->FETCHSIZE;
400 if ($self->{autodefer}) {
401 $self->_annotate_ad_history('SPLICE');
404 $self->_flush if $self->_is_deferring; # move this up?
406 $self->_chomp(my @a = $self->_splice(@_));
409 $self->_chomp1(scalar $self->_splice(@_));
415 $self->flush if $self->_is_deferring;
416 $self->{cache}->delink if defined $self->{cache}; # break circular link
420 my ($self, $pos, $nrecs, @data) = @_;
423 $pos = 0 unless defined $pos;
425 # Deal with negative and other out-of-range positions
426 # Also set default for $nrecs
428 my $oldsize = $self->FETCHSIZE;
429 $nrecs = $oldsize unless defined $nrecs;
435 croak "Modification of non-creatable array value attempted, subscript $oldpos";
439 if ($pos > $oldsize) {
441 $pos = $oldsize; # This is what perl does for normal arrays
445 $self->_fixrecs(@data);
446 my $data = join '', @data;
447 my $datalen = length $data;
450 # compute length of data being removed
451 for ($pos .. $pos+$nrecs-1) {
452 last unless defined $self->_fill_offsets_to($_);
453 my $rec = $self->_fetch($_);
454 last unless defined $rec;
457 # Why don't we just use length($rec) here?
458 # Because that record might have come from the cache. _splice
459 # might have been called to flush out the deferred-write records,
460 # and in this case length($rec) is the length of the record to be
461 # *written*, not the length of the actual record in the file. But
462 # the offsets are still true. 20020322
463 $oldlen += $self->{offsets}[$_+1] - $self->{offsets}[$_]
464 if defined $self->{offsets}[$_+1];
468 $self->_twrite($data, $self->{offsets}[$pos], $oldlen);
470 # update the offsets table part 1
471 # compute the offsets of the new records:
474 push @new_offsets, $self->{offsets}[$pos];
475 for (0 .. $#data-1) {
476 push @new_offsets, $new_offsets[-1] + length($data[$_]);
480 # If we're about to splice out the end of the offsets table...
481 if ($pos + $nrecs >= @{$self->{offsets}}) {
482 $self->{eof} = 0; # ... the table is no longer complete
484 splice(@{$self->{offsets}}, $pos, $nrecs, @new_offsets);
486 # update the offsets table part 2
487 # adjust the offsets of the following old records
488 for ($pos+@data .. $#{$self->{offsets}}) {
489 $self->{offsets}[$_] += $datalen - $oldlen;
491 # If we scrubbed out all known offsets, regenerate the trivial table
492 # that knows that the file does indeed start at 0.
493 $self->{offsets}[0] = 0 unless @{$self->{offsets}};
494 # If the file got longer, the offsets table is no longer complete
495 $self->{eof} = 0 if @data > $nrecs;
498 # Perhaps the following cache foolery could be factored out
499 # into a bunch of mor opaque cache functions. For example,
500 # it's odd to delete a record from the cache and then remove
501 # it from the LRU queue later on; there should be a function to
504 # update the read cache, part 1
506 for ($pos .. $pos+$nrecs-1) {
507 my $new = $data[$_-$pos];
509 $self->{cache}->update($_, $new);
511 $self->{cache}->remove($_);
515 # update the read cache, part 2
516 # moved records - records past the site of the change
517 # need to be renumbered
518 # Maybe merge this with the previous block?
520 my @oldkeys = grep $_ >= $pos + $nrecs, $self->{cache}->keys;
521 my @newkeys = map $_-$nrecs+@data, @oldkeys;
522 $self->{cache}->rekey(\@oldkeys, \@newkeys);
525 # Now there might be too much data in the cache, if we spliced out
526 # some short records and spliced in some long ones. If so, flush
530 # Yes, the return value of 'splice' *is* actually this complicated
531 wantarray ? @result : @result ? $result[-1] : undef;
534 # write data into the file
535 # $data is the data to be written.
536 # it should be written at position $pos, and should overwrite
537 # exactly $len of the following bytes.
538 # Note that if length($data) > $len, the subsequent bytes will have to
539 # be moved up, and if length($data) < $len, they will have to
542 my ($self, $data, $pos, $len) = @_;
544 unless (defined $pos) {
545 die "\$pos was undefined in _twrite";
548 my $len_diff = length($data) - $len;
550 if ($len_diff == 0) { # Woo-hoo!
551 my $fh = $self->{fh};
553 $self->_write_record($data);
554 return; # well, that was easy.
557 # the two records are of different lengths
558 # our strategy here: rewrite the tail of the file,
559 # reading ahead one buffer at a time
560 # $bufsize is required to be at least as large as the data we're overwriting
561 my $bufsize = _bufsize($len_diff);
562 my ($writepos, $readpos) = ($pos, $pos+$len);
566 # Seems like there ought to be a way to avoid the repeated code
567 # and the special case here. The read(1) is also a little weird.
570 $self->_seekb($readpos);
571 my $br = read $self->{fh}, $next_block, $bufsize;
572 $more_data = read $self->{fh}, my($dummy), 1;
573 $self->_seekb($writepos);
574 $self->_write_record($data);
576 $writepos += length $data;
578 } while $more_data; # BUG XXX TODO how could this have worked?
579 $self->_seekb($writepos);
580 $self->_write_record($next_block);
582 # There might be leftover data at the end of the file
583 $self->_chop_file if $len_diff < 0;
586 # If a record does not already end with the appropriate terminator
587 # string, append one.
591 $_ = "" unless defined $_;
592 $_ .= $self->{recsep}
593 unless substr($_, - $self->{recseplen}) eq $self->{recsep};
598 ################################################################
600 # Basic read, write, and seek
603 # seek to the beginning of record #$n
604 # Assumes that the offsets table is already correctly populated
606 # Note that $n=-1 has a special meaning here: It means the start of
607 # the last known record; this may or may not be the very last record
608 # in the file, depending on whether the offsets table is fully populated.
612 my $o = $self->{offsets}[$n];
614 or confess("logic error: undefined offset for record $n");
615 seek $self->{fh}, $o, SEEK_SET
616 or die "Couldn't seek filehandle: $!"; # "Should never happen."
621 seek $self->{fh}, $b, SEEK_SET
622 or die "Couldn't seek filehandle: $!"; # "Should never happen."
625 # populate the offsets table up to the beginning of record $n
626 # return the offset of record $n
627 sub _fill_offsets_to {
630 return $self->{offsets}[$n] if $self->{eof};
632 my $fh = $self->{fh};
633 local *OFF = $self->{offsets};
636 until ($#OFF >= $n) {
638 $self->_seek(-1); # tricky -- see comment at _seek
639 $rec = $self->_read_record;
644 return; # It turns out there is no such record
648 # we have now read all the records up to record n-1,
649 # so we can return the offset of record n
653 # assumes that $rec is already suitably terminated
655 my ($self, $rec) = @_;
656 my $fh = $self->{fh};
658 or die "Couldn't write record: $!"; # "Should never happen."
659 # $self->{_written} += length($rec);
665 { local $/ = $self->{recsep};
666 my $fh = $self->{fh};
669 return unless defined $rec;
670 if (substr($rec, -$self->{recseplen}) ne $self->{recsep}) {
671 # improperly terminated final record --- quietly fix it.
672 # my $ac = substr($rec, -$self->{recseplen});
674 unless ($self->{rdonly}) {
675 my $fh = $self->{fh};
676 print $fh $self->{recsep};
678 $rec .= $self->{recsep};
680 # $self->{_read} += length($rec) if defined $rec;
686 @{$self}{'_read', '_written'};
689 ################################################################
691 # Read cache management
695 $self->{cache}->reduce_size_to($self->{memory} - $self->{deferred_s});
698 sub _cache_too_full {
700 $self->{cache}->bytes + $self->{deferred_s} >= $self->{memory};
703 ################################################################
705 # File custodial services
709 # We have read to the end of the file and have the offsets table
710 # entirely populated. Now we need to write a new record beyond
711 # the end of the file. We prepare for this by writing
712 # empty records into the file up to the position we want
714 # assumes that the offsets table already contains the offset of record $n,
715 # if it exists, and extends to the end of the file if not.
716 sub _extend_file_to {
718 $self->_seek(-1); # position after the end of the last record
719 my $pos = $self->{offsets}[-1];
721 # the offsets table has one entry more than the total number of records
722 my $extras = $n - $#{$self->{offsets}};
724 # Todo : just use $self->{recsep} x $extras here?
725 while ($extras-- > 0) {
726 $self->_write_record($self->{recsep});
727 push @{$self->{offsets}}, tell $self->{fh};
731 # Truncate the file at the current position
734 truncate $self->{fh}, tell($self->{fh});
738 # compute the size of a buffer suitable for moving
739 # all the data in a file forward $n bytes
740 # ($n may be negative)
741 # The result should be at least $n.
744 return 8192 if $n < 0;
746 $b += 8192 if $n & 8191;
750 ################################################################
752 # Miscellaneous public methods
757 my ($self, $op) = @_;
759 my $pack = ref $self;
760 croak "Usage: $pack\->flock([OPERATION])";
762 my $fh = $self->{fh};
763 $op = LOCK_EX unless defined $op;
767 # Get/set autochomp option
771 my $old = $self->{autochomp};
772 $self->{autochomp} = shift;
779 ################################################################
781 # Matters related to deferred writing
787 $self->_stop_autodeferring;
788 @{$self->{ad_history}} = ();
792 # Flush deferred writes
794 # This could be better optimized to write the file in one pass, instead
795 # of one pass per block of records. But that will require modifications
796 # to _twrite, so I should have a good _twite test suite first.
806 my @writable = sort {$a<=>$b} (keys %{$self->{deferred}});
809 # gather all consecutive records from the front of @writable
810 my $first_rec = shift @writable;
811 my $last_rec = $first_rec+1;
812 ++$last_rec, shift @writable while @writable && $last_rec == $writable[0];
814 $self->_fill_offsets_to($last_rec);
815 $self->_extend_file_to($last_rec);
816 $self->_splice($first_rec, $last_rec-$first_rec+1,
817 @{$self->{deferred}}{$first_rec .. $last_rec});
820 $self->_discard; # clear out defered-write-cache
823 # Discard deferred writes and disable future deferred writes
830 # Discard deferred writes, but retain old deferred writing mode
833 %{$self->{deferred}} = ();
834 $self->{deferred_s} = 0;
835 $self->{deferred_max} = -1;
836 $self->{cache}->set_limit($self->{memory});
839 # Deferred writing is enabled, either explicitly ($self->{defer})
840 # or automatically ($self->{autodeferring})
843 $self->{defer} || $self->{autodeferring};
846 # The largest record number of any deferred record
849 return $self->{deferred_max} if defined $self->{deferred_max};
851 for my $key (keys %{$self->{deferred}}) {
852 $max = $key if $key > $max;
854 $self->{deferred_max} = $max;
858 ################################################################
860 # Matters related to autodeferment
863 # Get/set autodefer option
867 my $old = $self->{autodefer};
868 $self->{autodefer} = shift;
870 $self->_stop_autodeferring;
871 @{$self->{ad_history}} = ();
879 # The user is trying to store record #$n Record that in the history,
880 # and then enable (or disable) autodeferment if that seems useful.
881 # Note that it's OK for $n to be a non-number, as long as the function
882 # is prepared to deal with that. Nobody else looks at the ad_history.
884 # Now, what does the ad_history mean, and what is this function doing?
885 # Essentially, the idea is to enable autodeferring when we see that the
886 # user has made three consecutive STORE calls to three consecutive records.
887 # ("Three" is actually ->{autodefer_threshhold}.)
888 # A STORE call for record #$n inserts $n into the autodefer history,
889 # and if the history contains three consecutive records, we enable
890 # autodeferment. An ad_history of [X, Y] means that the most recent
891 # STOREs were for records X, X+1, ..., Y, in that order.
893 # Inserting a nonconsecutive number erases the history and starts over.
895 # Performing a special operation like SPLICE erases the history.
897 # There's one special case: CLEAR means that CLEAR was just called.
898 # In this case, we prime the history with [-2, -1] so that if the next
899 # write is for record 0, autodeferring goes on immediately. This is for
900 # the common special case of "@a = (...)".
902 sub _annotate_ad_history {
904 return unless $self->{autodefer}; # feature is disabled
905 return if $self->{defer}; # already in explicit defer mode
906 return unless $self->{offsets}[-1] >= $self->{autodefer_filelen_threshhold};
908 local *H = $self->{ad_history};
910 @H = (-2, -1); # prime the history with fake records
911 $self->_stop_autodeferring;
912 } elsif ($n =~ /^\d+$/) {
916 if ($H[1] == $n-1) { # another consecutive record
918 if ($H[1] - $H[0] + 1 >= $self->{autodefer_threshhold}) {
919 $self->{autodeferring} = 1;
921 } else { # nonconsecutive- erase and start over
923 $self->_stop_autodeferring;
926 } else { # SPLICE or STORESIZE or some such
928 $self->_stop_autodeferring;
932 # If autodferring was enabled, cut it out and discard the history
933 sub _stop_autodeferring {
935 if ($self->{autodeferring}) {
938 $self->{autodeferring} = 0;
941 ################################################################
944 # This is NOT a method. It is here for two reasons:
945 # 1. To factor a fairly complicated block out of the constructor
946 # 2. To provide access for the test suite, which need to be sure
947 # files are being written properly.
948 sub _default_recsep {
950 if ($^O eq 'MSWin32') { # Dos too?
951 # Windows users expect files to be terminated with \r\n
952 # But $/ is set to \n instead
953 # Note that this also transforms \n\n into \r\n\r\n.
955 $recsep =~ s/\n/\r\n/g;
960 # Utility function for _check_integrity
968 # Given a file, make sure the cache is consistent with the
969 # file contents and the internal data structures are consistent with
970 # each other. Returns true if everything checks out, false if not
972 # The $file argument is no longer used. It is retained for compatibility
973 # with the existing test suite.
974 sub _check_integrity {
975 my ($self, $file, $warn) = @_;
976 my $rsl = $self->{recseplen};
977 my $rs = $self->{recsep};
979 local *_; # local $_ does not work here
980 local $DIAGNOSTIC = 1;
982 if (not defined $rs) {
983 _ci_warn("recsep is undef!");
985 } elsif ($rs eq "") {
986 _ci_warn("recsep is empty!");
988 } elsif ($rsl != length $rs) {
990 _ci_warn("recsep <$rs> has length $ln, should be $rsl");
994 if (not defined $self->{offsets}[0]) {
995 _ci_warn("offset 0 is missing!");
997 } elsif ($self->{offsets}[0] != 0) {
998 _ci_warn("rec 0: offset <$self->{offsets}[0]> s/b 0!");
1004 local *F = $self->{fh};
1005 seek F, 0, SEEK_SET;
1011 my $cached = $self->{cache}->_produce($n);
1012 my $offset = $self->{offsets}[$.];
1014 if (defined $offset && $offset != $ao) {
1015 _ci_warn("rec $n: offset <$offset> actual <$ao>");
1018 if (defined $cached && $_ ne $cached && ! $self->{deferred}{$n}) {
1020 _ci_warn("rec $n: cached <$cached> actual <$_>");
1022 if (defined $cached && substr($cached, -$rsl) ne $rs) {
1024 _ci_warn("rec $n in the cache is missing the record separator");
1026 if (! defined $offset && $self->{eof}) {
1028 _ci_warn("The offset table was marked complete, but it is missing element $.");
1031 if (@{$self->{offsets}} > $.+1) {
1033 my $n = @{$self->{offsets}};
1034 _ci_warn("The offset table has $n items, but the file has only $.");
1037 my $deferring = $self->_is_deferring;
1038 for my $n ($self->{cache}->keys) {
1039 my $r = $self->{cache}->_produce($n);
1040 $cached += length($r);
1041 next if $n+1 <= $.; # checked this already
1042 _ci_warn("spurious caching of record $n");
1045 my $b = $self->{cache}->bytes;
1046 if ($cached != $b) {
1047 _ci_warn("cache size is $b, should be $cached");
1052 $good = 0 unless $self->{cache}->_check_integrity;
1054 # Now let's check the deferbuffer
1055 # Unless deferred writing is enabled, it should be empty
1056 if (! $self->_is_deferring && %{$self->{deferred}}) {
1057 _ci_warn("deferred writing disabled, but deferbuffer nonempty");
1061 # Any record in the deferbuffer should *not* be present in the readcache
1063 while (my ($n, $r) = each %{$self->{deferred}}) {
1064 $deferred_s += length($r);
1065 if (defined $self->{cache}->_produce($n)) {
1066 _ci_warn("record $n is in the deferbuffer *and* the readcache");
1069 if (substr($r, -$rsl) ne $rs) {
1070 _ci_warn("rec $n in the deferbuffer is missing the record separator");
1075 # Total size of deferbuffer should match internal total
1076 if ($deferred_s != $self->{deferred_s}) {
1077 _ci_warn("buffer size is $self->{deferred_s}, should be $deferred_s");
1081 # Total size of deferbuffer should not exceed the specified limit
1082 if ($deferred_s > $self->{dw_size}) {
1083 _ci_warn("buffer size is $self->{deferred_s} which exceeds the limit of $self->{dw_size}");
1087 # Total size of cached data should not exceed the specified limit
1088 if ($deferred_s + $cached > $self->{memory}) {
1089 my $total = $deferred_s + $cached;
1090 _ci_warn("total stored data size is $total which exceeds the limit of $self->{memory}");
1094 # Stuff related to autodeferment
1095 if (!$self->{autodefer} && @{$self->{ad_history}}) {
1096 _ci_warn("autodefer is disabled, but ad_history is nonempty");
1099 if ($self->{autodeferring} && $self->{defer}) {
1100 _ci_warn("both autodeferring and explicit deferring are active");
1103 if (@{$self->{ad_history}} == 0) {
1104 # That's OK, no additional tests required
1105 } elsif (@{$self->{ad_history}} == 2) {
1106 my @non_number = grep !/^-?\d+$/, @{$self->{ad_history}};
1110 $msg = "ad_history contains non-numbers (@{$self->{ad_history}})";
1114 } elsif ($self->{ad_history}[1] < $self->{ad_history}[0]) {
1115 _ci_warn("ad_history has nonsensical values @{$self->{ad_history}}");
1119 _ci_warn("ad_history has bad length <@{$self->{ad_history}}>");
1126 ################################################################
1132 package Tie::File::Cache;
1133 $Tie::File::Cache::VERSION = $Tie::File::VERSION;
1134 use Carp ':DEFAULT', 'confess';
1143 my ($pack, $max) = @_;
1145 croak "missing argument to ->new" unless defined $max;
1147 bless $self => $pack;
1148 @$self = (Tie::File::Heap->new($self), {}, $max, 0);
1153 my ($self, $n) = @_;
1158 my ($self, $n) = @_;
1162 # For internal use only
1163 # Will be called by the heap structure to notify us that a certain
1164 # piece of data has moved from one heap element to another.
1165 # $k is the hash key of the item
1166 # $n is the new index into the heap at which it is stored
1167 # If $n is undefined, the item has been removed from the heap.
1169 my ($self, $k, $n) = @_;
1171 $self->[HASH]{$k} = $n;
1173 delete $self->[HASH]{$k};
1178 my ($self, $key, $val) = @_;
1180 croak "missing argument to ->insert" unless defined $key;
1181 unless (defined $self->[MAX]) {
1182 confess "undefined max" ;
1184 confess "undefined val" unless defined $val;
1185 return if length($val) > $self->[MAX];
1186 my $oldnode = $self->[HASH]{$key};
1187 if (defined $oldnode) {
1188 my $oldval = $self->[HEAP]->set_val($oldnode, $val);
1189 $self->[BYTES] -= length($oldval);
1191 $self->[HEAP]->insert($key, $val);
1193 $self->[BYTES] += length($val);
1199 my $old_data = $self->[HEAP]->popheap;
1200 return unless defined $old_data;
1201 $self->[BYTES] -= length $old_data;
1206 my ($self, @keys) = @_;
1208 for my $key (@keys) {
1209 next unless exists $self->[HASH]{$key};
1210 my $old_data = $self->[HEAP]->remove($self->[HASH]{$key});
1211 $self->[BYTES] -= length $old_data;
1212 push @result, $old_data;
1218 my ($self, $key) = @_;
1220 croak "missing argument to ->lookup" unless defined $key;
1221 if (exists $self->[HASH]{$key}) {
1222 $self->[HEAP]->lookup($self->[HASH]{$key});
1228 # For internal use only
1230 my ($self, $key) = @_;
1231 my $loc = $self->[HASH]{$key};
1232 return unless defined $loc;
1233 $self->[HEAP][$loc][2];
1236 # For internal use only
1238 my ($self, $key) = @_;
1239 $self->[HEAP]->promote($self->[HASH]{$key});
1244 %{$self->[HASH]} = ();
1246 $self->[HEAP]->empty;
1251 keys %{$self->[HASH]} == 0;
1255 my ($self, $key, $val) = @_;
1257 croak "missing argument to ->update" unless defined $key;
1258 if (length($val) > $self->[MAX]) {
1259 my $oldval = $self->remove($key);
1260 $self->[BYTES] -= length($oldval) if defined $oldval;
1261 } elsif (exists $self->[HASH]{$key}) {
1262 my $oldval = $self->[HEAP]->set_val($self->[HASH]{$key}, $val);
1263 $self->[BYTES] += length($val);
1264 $self->[BYTES] -= length($oldval) if defined $oldval;
1266 $self->[HEAP]->insert($key, $val);
1267 $self->[BYTES] += length($val);
1273 my ($self, $okeys, $nkeys) = @_;
1276 @map{@$okeys} = @$nkeys;
1277 croak "missing argument to ->rekey" unless defined $nkeys;
1278 croak "length mismatch in ->rekey arguments" unless @$nkeys == @$okeys;
1279 my %adjusted; # map new keys to heap indices
1280 # You should be able to cut this to one loop TODO XXX
1281 for (0 .. $#$okeys) {
1282 $adjusted{$nkeys->[$_]} = delete $self->[HASH]{$okeys->[$_]};
1284 while (my ($nk, $ix) = each %adjusted) {
1285 # @{$self->[HASH]}{keys %adjusted} = values %adjusted;
1286 $self->[HEAP]->rekey($ix, $nk);
1287 $self->[HASH]{$nk} = $ix;
1293 my @a = keys %{$self->[HASH]};
1302 sub reduce_size_to {
1303 my ($self, $max) = @_;
1304 until ($self->is_empty || $self->[BYTES] <= $max) {
1311 until ($self->is_empty || $self->[BYTES] <= $self->[MAX]) {
1316 # For internal use only
1319 $self->[HEAP]->expire_order;
1322 sub _check_integrity {
1324 $self->[HEAP]->_check_integrity;
1329 $self->[HEAP] = undef; # Bye bye heap
1332 ################################################################
1336 # Heap data structure for use by cache LRU routines
1338 package Tie::File::Heap;
1339 use Carp ':DEFAULT', 'confess';
1340 $Tie::File::Heap::VERSION = $Tie::File::Cache::VERSION;
1346 my ($pack, $cache) = @_;
1347 die "$pack: Parent cache object $cache does not support _heap_move method"
1348 unless eval { $cache->can('_heap_move') };
1349 my $self = [[0,$cache,0]];
1350 bless $self => $pack;
1353 # Allocate a new sequence number, larger than all previously allocated numbers
1388 $self->[0][0] = 0; # might as well reset the sequence numbers
1391 # notify the parent cache object that we moved something
1394 $self->_cache->_heap_move(@_);
1397 # Insert a piece of data into the heap with the indicated sequence number.
1398 # The item with the smallest sequence number is always at the top.
1399 # If no sequence number is specified, allocate a new one and insert the
1400 # item at the bottom.
1402 my ($self, $key, $data, $seq) = @_;
1403 $seq = $self->_nseq unless defined $seq;
1404 $self->_insert_new([$seq, $key, $data]);
1407 # Insert a new, fresh item at the bottom of the heap
1409 my ($self, $item) = @_;
1411 $i = int($i/2) until defined $self->[$i/2];
1412 $self->[$i] = $item;
1413 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1417 # Insert [$data, $seq] pair at or below item $i in the heap.
1418 # If $i is omitted, default to 1 (the top element.)
1420 my ($self, $item, $i) = @_;
1421 $self->_check_loc($i) if defined $i;
1422 $i = 1 unless defined $i;
1423 until (! defined $self->[$i]) {
1424 if ($self->[$i][SEQ] > $item->[SEQ]) { # inserted item is older
1425 ($self->[$i], $item) = ($item, $self->[$i]);
1426 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1428 # If either is undefined, go that way. Otherwise, choose at random
1430 $dir = 0 if !defined $self->[2*$i];
1431 $dir = 1 if !defined $self->[2*$i+1];
1432 $dir = int(rand(2)) unless defined $dir;
1435 $self->[$i] = $item;
1436 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1440 # Remove the item at node $i from the heap, moving child items upwards.
1441 # The item with the smallest sequence number is always at the top.
1442 # Moving items upwards maintains this condition.
1443 # Return the removed item.
1445 my ($self, $i) = @_;
1446 $i = 1 unless defined $i;
1447 my $top = $self->[$i];
1448 return unless defined $top;
1451 my ($L, $R) = (2*$i, 2*$i+1);
1453 # If either is undefined, go the other way.
1454 # Otherwise, go towards the smallest.
1455 last unless defined $self->[$L] || defined $self->[$R];
1456 $ii = $R if not defined $self->[$L];
1457 $ii = $L if not defined $self->[$R];
1458 unless (defined $ii) {
1459 $ii = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
1462 $self->[$i] = $self->[$ii]; # Promote child to fill vacated spot
1463 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
1464 $i = $ii; # Fill new vacated spot
1466 $self->[0][1]->_heap_move($top->[KEY], undef);
1477 # set the sequence number of the indicated item to a higher number
1478 # than any other item in the heap, and bubble the item down to the
1481 my ($self, $n) = @_;
1482 $self->_check_loc($n);
1483 $self->[$n][SEQ] = $self->_nseq;
1486 my ($L, $R) = (2*$i, 2*$i+1);
1488 last unless defined $self->[$L] || defined $self->[$R];
1489 $dir = $R unless defined $self->[$L];
1490 $dir = $L unless defined $self->[$R];
1491 unless (defined $dir) {
1492 $dir = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
1494 @{$self}[$i, $dir] = @{$self}[$dir, $i];
1496 $self->[0][1]->_heap_move($self->[$_][KEY], $_) if defined $self->[$_];
1502 # Return item $n from the heap, promoting its LRU status
1504 my ($self, $n) = @_;
1505 $self->_check_loc($n);
1506 my $val = $self->[$n];
1512 # Assign a new value for node $n, promoting it to the bottom of the heap
1514 my ($self, $n, $val) = @_;
1515 $self->_check_loc($n);
1516 my $oval = $self->[$n][DAT];
1517 $self->[$n][DAT] = $val;
1522 # The hask key has changed for an item;
1523 # alter the heap's record of the hash key
1525 my ($self, $n, $new_key) = @_;
1526 $self->_check_loc($n);
1527 $self->[$n][KEY] = $new_key;
1531 my ($self, $n) = @_;
1532 unless (defined $self->[$n]) {
1533 confess "_check_loc($n) failed";
1537 sub _check_integrity {
1540 unless (eval {$self->[0][1]->isa("Tie::File::Cache")}) {
1541 print "# Element 0 of heap corrupt\n";
1544 $good = 0 unless $self->_satisfies_heap_condition(1);
1545 for my $i (2 .. $#{$self}) {
1546 my $p = int($i/2); # index of parent node
1547 if (defined $self->[$i] && ! defined $self->[$p]) {
1548 print "# Element $i of heap defined, but parent $p isn't\n";
1555 sub _satisfies_heap_condition {
1561 next unless defined $self->[$c];
1562 if ($self->[$n][SEQ] >= $self->[$c]) {
1563 print "# Node $n of heap does not predate node $c\n";
1566 $good = 0 unless $self->_satisfies_heap_condition($c);
1571 # Return a list of all the values, sorted by expiration order
1574 my @nodes = sort {$a->[SEQ] <=> $b->[SEQ]} $self->_nodes;
1575 map { $_->[KEY] } @nodes;
1581 return unless defined $self->[$i];
1582 ($self->[$i], $self->_nodes($i*2), $self->_nodes($i*2+1));
1585 "Cogito, ergo sum."; # don't forget to return a true value from the file
1589 Tie::File - Access the lines of a disk file via a Perl array
1593 # This file documents Tie::File version 0.90
1595 tie @array, 'Tie::File', filename or die ...;
1597 $array[13] = 'blah'; # line 13 of the file is now 'blah'
1598 print $array[42]; # display line 42 of the file
1600 $n_recs = @array; # how many records are in the file?
1601 $#array -= 2; # chop two records off the end
1605 s/PERL/Perl/g; # Replace PERL with Perl everywhere in the file
1608 # These are just like regular push, pop, unshift, shift, and splice
1609 # Except that they modify the file in the way you would expect
1611 push @array, new recs...;
1612 my $r1 = pop @array;
1613 unshift @array, new recs...;
1614 my $r1 = shift @array;
1615 @old_recs = splice @array, 3, 7, new recs...;
1617 untie @array; # all finished
1622 C<Tie::File> represents a regular text file as a Perl array. Each
1623 element in the array corresponds to a record in the file. The first
1624 line of the file is element 0 of the array; the second line is element
1627 The file is I<not> loaded into memory, so this will work even for
1630 Changes to the array are reflected in the file immediately.
1632 Lazy people and beginners may now stop reading the manual.
1636 What is a 'record'? By default, the meaning is the same as for the
1637 C<E<lt>...E<gt>> operator: It's a string terminated by C<$/>, which is
1638 probably C<"\n">. (Minor exception: on dos and Win32 systems, a
1639 'record' is a string terminated by C<"\r\n">.) You may change the
1640 definition of "record" by supplying the C<recsep> option in the C<tie>
1643 tie @array, 'Tie::File', $file, recsep => 'es';
1645 This says that records are delimited by the string C<es>. If the file
1646 contained the following data:
1648 Curse these pesky flies!\n
1650 then the C<@array> would appear to have four elements:
1657 An undefined value is not permitted as a record separator. Perl's
1658 special "paragraph mode" semantics (E<agrave> la C<$/ = "">) are not
1661 Records read from the tied array do not have the record separator
1662 string on the end; this is to allow
1664 $array[17] .= "extra";
1666 to work as expected.
1668 (See L<"autochomp">, below.) Records stored into the array will have
1669 the record separator string appended before they are written to the
1670 file, if they don't have one already. For example, if the record
1671 separator string is C<"\n">, then the following two lines do exactly
1674 $array[17] = "Cherry pie";
1675 $array[17] = "Cherry pie\n";
1677 The result is that the contents of line 17 of the file will be
1678 replaced with "Cherry pie"; a newline character will separate line 17
1679 from line 18. This means that this code will do nothing:
1683 Because the C<chomp>ed value will have the separator reattached when
1684 it is written back to the file. There is no way to create a file
1685 whose trailing record separator string is missing.
1687 Inserting records that I<contain> the record separator string is not
1688 supported by this module. It will probably produce a reasonable
1689 result, but what this result will be may change in a future version.
1690 Use 'splice' to insert records or to replace one record with several.
1694 Normally, array elements have the record separator removed, so that if
1695 the file contains the text
1701 the tied array will appear to contain C<("Gold", "Frankincense",
1702 "Myrrh")>. If you set C<autochomp> to a false value, the record
1703 separator will not be removed. If the file above was tied with
1705 tie @gifts, "Tie::File", $gifts, autochomp => 0;
1707 then the array C<@gifts> would appear to contain C<("Gold\n",
1708 "Frankincense\n", "Myrrh\n")>, or (on Win32 systems) C<("Gold\r\n",
1709 "Frankincense\r\n", "Myrrh\r\n")>.
1713 Normally, the specified file will be opened for read and write access,
1714 and will be created if it does not exist. (That is, the flags
1715 C<O_RDWR | O_CREAT> are supplied in the C<open> call.) If you want to
1716 change this, you may supply alternative flags in the C<mode> option.
1717 See L<Fcntl> for a listing of available flags.
1720 # open the file if it exists, but fail if it does not exist
1722 tie @array, 'Tie::File', $file, mode => O_RDWR;
1724 # create the file if it does not exist
1725 use Fcntl 'O_RDWR', 'O_CREAT';
1726 tie @array, 'Tie::File', $file, mode => O_RDWR | O_CREAT;
1728 # open an existing file in read-only mode
1729 use Fcntl 'O_RDONLY';
1730 tie @array, 'Tie::File', $file, mode => O_RDONLY;
1732 Opening the data file in write-only or append mode is not supported.
1736 This is an upper limit on the amount of memory that C<Tie::File> will
1737 consume at any time while managing the file. This is used for two
1738 things: managing the I<read cache> and managing the I<deferred write
1741 Records read in from the file are cached, to avoid having to re-read
1742 them repeatedly. If you read the same record twice, the first time it
1743 will be stored in memory, and the second time it will be fetched from
1744 the I<read cache>. The amount of data in the read cache will not
1745 exceed the value you specified for C<memory>. If C<Tie::File> wants
1746 to cache a new record, but the read cache is full, it will make room
1747 by expiring the least-recently visited records from the read cache.
1749 The default memory limit is 2Mib. You can adjust the maximum read
1750 cache size by supplying the C<memory> option. The argument is the
1751 desired cache size, in bytes.
1753 # I have a lot of memory, so use a large cache to speed up access
1754 tie @array, 'Tie::File', $file, memory => 20_000_000;
1756 Setting the memory limit to 0 will inhibit caching; records will be
1757 fetched from disk every time you examine them.
1759 The C<memory> value is not an absolute or exact limit on the memory
1760 used. C<Tie::File> objects contains some structures besides the read
1761 cache and the deferred write buffer, whose sizes are not charged
1766 (This is an advanced feature. Skip this section on first reading.)
1768 If you use deferred writing (See L<"Deferred Writing">, below) then
1769 data you write into the array will not be written directly to the
1770 file; instead, it will be saved in the I<deferred write buffer> to be
1771 written out later. Data in the deferred write buffer is also charged
1772 against the memory limit you set with the C<memory> option.
1774 You may set the C<dw_size> option to limit the amount of data that can
1775 be saved in the deferred write buffer. This limit may not exceed the
1776 total memory limit. For example, if you set C<dw_size> to 1000 and
1777 C<memory> to 2500, that means that no more than 1000 bytes of deferred
1778 writes will be saved up. The space available for the read cache will
1779 vary, but it will always be at least 1500 bytes (if the deferred write
1780 buffer is full) and it could grow as large as 2500 bytes (if the
1781 deferred write buffer is empty.)
1783 If you don't specify a C<dw_size>, it defaults to the entire memory
1786 =head2 Option Format
1788 C<-mode> is a synonym for C<mode>. C<-recsep> is a synonym for
1789 C<recsep>. C<-memory> is a synonym for C<memory>. You get the
1792 =head1 Public Methods
1794 The C<tie> call returns an object, say C<$o>. You may call
1796 $rec = $o->FETCH($n);
1797 $o->STORE($n, $rec);
1799 to fetch or store the record at line C<$n>, respectively; similarly
1800 the other tied array methods. (See L<perltie> for details.) You may
1801 also call the following methods on this object:
1807 will lock the tied file. C<MODE> has the same meaning as the second
1808 argument to the Perl built-in C<flock> function; for example
1809 C<LOCK_SH> or C<LOCK_EX | LOCK_NB>. (These constants are provided by
1810 the C<use Fcntl ':flock'> declaration.)
1812 C<MODE> is optional; the default is C<LOCK_EX>.
1814 C<Tie::File> promises that the following sequence of operations will
1817 my $o = tie @array, "Tie::File", $filename;
1820 In particular, C<Tie::File> will I<not> read or write the file during
1821 the C<tie> call. (Exception: Using C<mode =E<gt> O_TRUNC> will, of
1822 course, erase the file during the C<tie> call. If you want to do this
1823 safely, then open the file without C<O_TRUNC>, lock the file, and use
1826 The best way to unlock a file is to discard the object and untie the
1827 array. It is probably unsafe to unlock the file without also untying
1828 it, because if you do, changes may remain unwritten inside the object.
1829 That is why there is no shortcut for unlocking. If you really want to
1830 unlock the file prematurely, you know what to do; if you don't know
1831 what to do, then don't do it.
1833 All the usual warnings about file locking apply here. In particular,
1834 note that file locking in Perl is B<advisory>, which means that
1835 holding a lock will not prevent anyone else from reading, writing, or
1836 erasing the file; it only prevents them from getting another lock at
1837 the same time. Locks are analogous to green traffic lights: If you
1838 have a green light, that does not prevent the idiot coming the other
1839 way from plowing into you sideways; it merely guarantees to you that
1840 the idiot does not also have a green light at the same time.
1844 my $old_value = $o->autochomp(0); # disable autochomp option
1845 my $old_value = $o->autochomp(1); # enable autochomp option
1847 my $ac = $o->autochomp(); # recover current value
1849 See L<"autochomp">, above.
1851 =head2 C<defer>, C<flush>, C<discard>, and C<autodefer>
1853 See L<"Deferred Writing">, below.
1855 =head1 Tying to an already-opened filehandle
1857 If C<$fh> is a filehandle, such as is returned by C<IO::File> or one
1858 of the other C<IO> modules, you may use:
1860 tie @array, 'Tie::File', $fh, ...;
1862 Similarly if you opened that handle C<FH> with regular C<open> or
1863 C<sysopen>, you may use:
1865 tie @array, 'Tie::File', \*FH, ...;
1867 Handles that were opened write-only won't work. Handles that were
1868 opened read-only will work as long as you don't try to modify the
1869 array. Handles must be attached to seekable sources of data---that
1870 means no pipes or sockets. If C<Tie::File> can detect that you
1871 supplied a non-seekable handle, the C<tie> call will throw an
1872 exception. (On Unix systems, it can detect this.)
1874 =head1 Deferred Writing
1876 (This is an advanced feature. Skip this section on first reading.)
1878 Normally, modifying a C<Tie::File> array writes to the underlying file
1879 immediately. Every assignment like C<$a[3] = ...> rewrites as much of
1880 the file as is necessary; typically, everything from line 3 through
1881 the end will need to be rewritten. This is the simplest and most
1882 transparent behavior. Performance even for large files is reasonably
1885 However, under some circumstances, this behavior may be excessively
1886 slow. For example, suppose you have a million-record file, and you
1893 The first time through the loop, you will rewrite the entire file,
1894 from line 0 through the end. The second time through the loop, you
1895 will rewrite the entire file from line 1 through the end. The third
1896 time through the loop, you will rewrite the entire file from line 2 to
1899 If the performance in such cases is unacceptable, you may defer the
1900 actual writing, and then have it done all at once. The following loop
1901 will perform much better for large files:
1909 If C<Tie::File>'s memory limit is large enough, all the writing will
1910 done in memory. Then, when you call C<-E<gt>flush>, the entire file
1911 will be rewritten in a single pass.
1913 (Actually, the preceding discussion is something of a fib. You don't
1914 need to enable deferred writing to get good performance for this
1915 common case, because C<Tie::File> will do it for you automatically
1916 unless you specifically tell it not to. See L<"autodeferring">,
1919 Calling C<-E<gt>flush> returns the array to immediate-write mode. If
1920 you wish to discard the deferred writes, you may call C<-E<gt>discard>
1921 instead of C<-E<gt>flush>. Note that in some cases, some of the data
1922 will have been written already, and it will be too late for
1923 C<-E<gt>discard> to discard all the changes. Support for
1924 C<-E<gt>discard> may be withdrawn in a future version of C<Tie::File>.
1926 Deferred writes are cached in memory up to the limit specified by the
1927 C<dw_size> option (see above). If the deferred-write buffer is full
1928 and you try to write still more deferred data, the buffer will be
1929 flushed. All buffered data will be written immediately, the buffer
1930 will be emptied, and the now-empty space will be used for future
1933 If the deferred-write buffer isn't yet full, but the total size of the
1934 buffer and the read cache would exceed the C<memory> limit, the oldest
1935 records will be expired from the read cache until the total size is
1938 C<push>, C<pop>, C<shift>, C<unshift>, and C<splice> cannot be
1939 deferred. When you perform one of these operations, any deferred data
1940 is written to the file and the operation is performed immediately.
1941 This may change in a future version.
1943 If you resize the array with deferred writing enabled, the file will
1944 be resized immediately, but deferred records will not be written.
1945 This has a surprising consequence: C<@a = (...)> erases the file
1946 immediately, but the writing of the actual data is deferred. This
1947 might be a bug. If it is a bug, it will be fixed in a future version.
1949 =head2 Autodeferring
1951 C<Tie::File> tries to guess when deferred writing might be helpful,
1952 and to turn it on and off automatically.
1958 In this example, only the first two assignments will be done
1959 immediately; after this, all the changes to the file will be deferred
1960 up to the user-specified memory limit.
1962 You should usually be able to ignore this and just use the module
1963 without thinking about deferring. However, special applications may
1964 require fine control over which writes are deferred, or may require
1965 that all writes be immediate. To disable the autodeferment feature,
1968 (tied @o)->autodefer(0);
1972 tie @array, 'Tie::File', $file, autodefer => 0;
1975 Similarly, C<-E<gt>autodefer(1)> re-enables autodeferment, and
1976 C<-E<gt>autodefer()> recovers the current value of the autodefer setting.
1980 (That's Latin for 'warnings'.)
1986 This is BETA RELEASE SOFTWARE. It may have bugs. See the discussion
1987 below about the (lack of any) warranty.
1989 In particular, this means that the interface may change in
1990 incompatible ways from one version to the next, without warning. That
1991 has happened at least once already. The interface will freeze before
1992 Perl 5.8 is released, probably sometime in April 2002.
1996 Reasonable effort was made to make this module efficient. Nevertheless,
1997 changing the size of a record in the middle of a large file will
1998 always be fairly slow, because everything after the new record must be
2003 The behavior of tied arrays is not precisely the same as for regular
2004 arrays. For example:
2006 # This DOES print "How unusual!"
2007 undef $a[10]; print "How unusual!\n" if defined $a[10];
2009 C<undef>-ing a C<Tie::File> array element just blanks out the
2010 corresponding record in the file. When you read it back again, you'll
2011 get the empty string, so the supposedly-C<undef>'ed value will be
2012 defined. Similarly, if you have C<autochomp> disabled, then
2014 # This DOES print "How unusual!" if 'autochomp' is disabled
2016 print "How unusual!\n" if $a[10];
2018 Because when C<autochomp> is disabled, C<$a[10]> will read back as
2019 C<"\n"> (or whatever the record separator string is.)
2021 There are other minor differences, particularly regarding C<exists>
2022 and C<delete>, but in general, the correspondence is extremely close.
2026 Not quite every effort was made to make this module as efficient as
2027 possible. C<FETCHSIZE> should use binary search instead of linear
2030 The performance of the C<flush> method could be improved. At present,
2031 it still rewrites the tail of the file once for each block of
2032 contiguous lines to be changed. In the typical case, this will result
2033 in only one rewrite, but in peculiar cases it might be bad. It should
2034 be possible to perform I<all> deferred writing with a single rewrite.
2036 Profiling suggests that these defects are probably minor; in any
2037 event, they will be fixed in a future version of the module.
2041 I have supposed that since this module is concerned with file I/O,
2042 almost all normal use of it will be heavily I/O bound. This means
2043 that the time to maintain complicated data structures inside the
2044 module will be dominated by the time to actually perform the I/O.
2045 When there was an opportunity to spend CPU time to avoid doing I/O, I
2050 You might be tempted to think that deferred writing is like
2051 transactions, with C<flush> as C<commit> and C<discard> as
2052 C<rollback>, but it isn't, so don't.
2058 This version promises absolutely nothing about the internals, which
2059 may change without notice. A future version of the module will have a
2060 well-defined and stable subclassing API.
2062 =head1 WHAT ABOUT C<DB_File>?
2064 People sometimes point out that L<DB_File> will do something similar,
2065 and ask why C<Tie::File> module is necessary.
2067 There are a number of reasons that you might prefer C<Tie::File>.
2068 A list is available at C<http://perl.plover.com/TieFile/why-not-DB_File>.
2074 To contact the author, send email to: C<mjd-perl-tiefile+@plover.com>
2076 To receive an announcement whenever a new version of this module is
2077 released, send a blank email message to
2078 C<mjd-perl-tiefile-subscribe@plover.com>.
2080 The most recent version of this module, including documentation and
2081 any news of importance, will be available at
2083 http://perl.plover.com/TieFile/
2088 C<Tie::File> version 0.90 is copyright (C) 2002 Mark Jason Dominus.
2090 This library is free software; you may redistribute it and/or modify
2091 it under the same terms as Perl itself.
2093 These terms are your choice of any of (1) the Perl Artistic Licence,
2094 or (2) version 2 of the GNU General Public License as published by the
2095 Free Software Foundation, or (3) any later version of the GNU General
2098 This library is distributed in the hope that it will be useful,
2099 but WITHOUT ANY WARRANTY; without even the implied warranty of
2100 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2101 GNU General Public License for more details.
2103 You should have received a copy of the GNU General Public License
2104 along with this library program; it should be in the file C<COPYING>.
2105 If not, write to the Free Software Foundation, Inc., 59 Temple Place,
2106 Suite 330, Boston, MA 02111 USA
2108 For licensing inquiries, contact the author at:
2112 Philadelphia, PA 19107
2116 C<Tie::File> version 0.90 comes with ABSOLUTELY NO WARRANTY.
2117 For details, see the license.
2121 Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the
2122 core when I hadn't written it yet, and for generally being helpful,
2123 supportive, and competent. (Usually the rule is "choose any one.")
2124 Also big thanks to Abhijit Menon-Sen for all of the same things.
2126 Special thanks to Craig Berry and Peter Prymmer (for VMS portability
2127 help), Randy Kobes (for Win32 portability help), Clinton Pierce and
2128 Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond
2129 the call of duty), Michael G Schwern (for testing advice), and the
2130 rest of the CPAN testers (for testing generally).
2132 Additional thanks to:
2137 Tassilo von Parseval /
2142 Autrijus Tang (again) /
2148 More tests. (The cache and heap modules need more unit tests.)
2150 Improve SPLICE algorithm to use deferred writing machinery.
2152 Cleverer strategy for flushing deferred writes.
2154 More tests. (Stuff I didn't think of yet.)
2158 Fixed-length mode. Leave-blanks mode.
2160 Maybe an autolocking mode?
2162 Record locking with fcntl()? Then the module might support an undo
2163 log and get real transactions. What a tour de force that would be.