<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">
package Tie::File;
require 5.005;
use Carp ':DEFAULT', 'confess';
use POSIX 'SEEK_SET';
use Fcntl 'O_CREAT', 'O_RDWR', 'LOCK_EX', 'LOCK_SH', 'O_WRONLY', 'O_RDONLY';
sub O_ACCMODE () { O_RDONLY | O_RDWR | O_WRONLY }


$VERSION = "1.01";
my $DEFAULT_MEMORY_SIZE = 1&lt;&lt;21;    # 2 megabytes
my $DEFAULT_AUTODEFER_THRESHHOLD = 3; # 3 records
my $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD = 65536; # 16 disk blocksful

my %good_opt = map {$_ =&gt; 1, "-$_" =&gt; 1}
                 qw(memory dw_size mode recsep discipline 
                    autodefer autochomp autodefer_threshhold concurrent);

sub TIEARRAY {
  if (@_ % 2 != 0) {
    croak "usage: tie \@array, $_[0], filename, [option =&gt; value]...";
  }
  my ($pack, $file, %opts) = @_;

  # transform '-foo' keys into 'foo' keys
  for my $key (keys %opts) {
    unless ($good_opt{$key}) {
      croak("$pack: Unrecognized option '$key'\n");
    }
    my $okey = $key;
    if ($key =~ s/^-+//) {
      $opts{$key} = delete $opts{$okey};
    }
  }

  if ($opts{concurrent}) {
    croak("$pack: concurrent access not supported yet\n");
  }

  unless (defined $opts{memory}) {
    # default is the larger of the default cache size and the 
    # deferred-write buffer size (if specified)
    $opts{memory} = $DEFAULT_MEMORY_SIZE;
    $opts{memory} = $opts{dw_size}
      if defined $opts{dw_size} &amp;&amp; $opts{dw_size} &gt; $DEFAULT_MEMORY_SIZE;
    # Dora Winifred Read
  }
  $opts{dw_size} = $opts{memory} unless defined $opts{dw_size};
  if ($opts{dw_size} &gt; $opts{memory}) {
      croak("$pack: dw_size may not be larger than total memory allocation\n");
  }
  # are we in deferred-write mode?
  $opts{defer} = 0 unless defined $opts{defer};
  $opts{deferred} = {};         # no records are presently deferred
  $opts{deferred_s} = 0;        # count of total bytes in -&gt;{deferred}
  $opts{deferred_max} = -1;     # empty

  # What's a good way to arrange that this class can be overridden?
  $opts{cache} = Tie::File::Cache-&gt;new($opts{memory});

  # autodeferment is enabled by default
  $opts{autodefer} = 1 unless defined $opts{autodefer};
  $opts{autodeferring} = 0;     # but is not initially active
  $opts{ad_history} = [];
  $opts{autodefer_threshhold} = $DEFAULT_AUTODEFER_THRESHHOLD
    unless defined $opts{autodefer_threshhold};
  $opts{autodefer_filelen_threshhold} = $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD
    unless defined $opts{autodefer_filelen_threshhold};

  $opts{offsets} = [0];
  $opts{filename} = $file;
  unless (defined $opts{recsep}) { 
    $opts{recsep} = _default_recsep();
  }
  $opts{recseplen} = length($opts{recsep});
  if ($opts{recseplen} == 0) {
    croak "Empty record separator not supported by $pack";
  }

  $opts{autochomp} = 1 unless defined $opts{autochomp};

  $opts{mode} = O_CREAT|O_RDWR unless defined $opts{mode};
  $opts{rdonly} = (($opts{mode} &amp; O_ACCMODE) == O_RDONLY);
  $opts{sawlastrec} = undef;

  my $fh;

  if (UNIVERSAL::isa($file, 'GLOB')) {
    # We use 1 here on the theory that some systems 
    # may not indicate failure if we use 0.
    # MSWin32 does not indicate failure with 0, but I don't know if
    # it will indicate failure with 1 or not.
    unless (seek $file, 1, SEEK_SET) {
      croak "$pack: your filehandle does not appear to be seekable";
    }
    seek $file, 0, SEEK_SET;    # put it back
    $fh = $file;                # setting binmode is the user's problem
  } elsif (ref $file) {
    croak "usage: tie \@array, $pack, filename, [option =&gt; value]...";
  } else {
    # $fh = \do { local *FH };  # XXX this is buggy
    if ($] &lt; 5.006) {
	# perl 5.005 and earlier don't autovivify filehandles
	require Symbol;
	$fh = Symbol::gensym();
    }
    sysopen $fh, $file, $opts{mode}, 0666 or return;
    binmode $fh;
    ++$opts{ourfh};
  }
  { my $ofh = select $fh; $| = 1; select $ofh } # autoflush on write
  if (defined $opts{discipline} &amp;&amp; $] &gt;= 5.006) {
    # This avoids a compile-time warning under 5.005
    eval 'binmode($fh, $opts{discipline})';
    croak $@ if $@ =~ /unknown discipline/i;
    die if $@;
  }
  $opts{fh} = $fh;

  bless \%opts =&gt; $pack;
}

sub FETCH {
  my ($self, $n) = @_;
  my $rec;

  # check the defer buffer
  $rec = $self-&gt;{deferred}{$n} if exists $self-&gt;{deferred}{$n};
  $rec = $self-&gt;_fetch($n) unless defined $rec;

  # inlined _chomp1
  substr($rec, - $self-&gt;{recseplen}) = ""
    if defined $rec &amp;&amp; $self-&gt;{autochomp};
  $rec;
}

# Chomp many records in-place; return nothing useful
sub _chomp {
  my $self = shift;
  return unless $self-&gt;{autochomp};
  if ($self-&gt;{autochomp}) {
    for (@_) {
      next unless defined;
      substr($_, - $self-&gt;{recseplen}) = "";
    }
  }
}

# Chomp one record in-place; return modified record
sub _chomp1 {
  my ($self, $rec) = @_;
  return $rec unless $self-&gt;{autochomp};
  return unless defined $rec;
  substr($rec, - $self-&gt;{recseplen}) = "";
  $rec;
}

sub _fetch {
  my ($self, $n) = @_;

  # check the record cache
  { my $cached = $self-&gt;{cache}-&gt;lookup($n);
    return $cached if defined $cached;
  }

  if ($#{$self-&gt;{offsets}} &lt; $n) {
    return if $self-&gt;{eof};  # request for record beyond end of file
    my $o = $self-&gt;_fill_offsets_to($n);
    # If it's still undefined, there is no such record, so return 'undef'
    return unless defined $o;
  }

  my $fh = $self-&gt;{FH};
  $self-&gt;_seek($n);             # we can do this now that offsets is populated
  my $rec = $self-&gt;_read_record;

# If we happen to have just read the first record, check to see if
# the length of the record matches what 'tell' says.  If not, Tie::File
# won't work, and should drop dead.
#
#  if ($n == 0 &amp;&amp; defined($rec) &amp;&amp; tell($self-&gt;{fh}) != length($rec)) {
#    if (defined $self-&gt;{discipline}) {
#      croak "I/O discipline $self-&gt;{discipline} not supported";
#    } else {
#      croak "File encoding not supported";
#    }
#  }

  $self-&gt;{cache}-&gt;insert($n, $rec) if defined $rec &amp;&amp; not $self-&gt;{flushing};
  $rec;
}

sub STORE {
  my ($self, $n, $rec) = @_;
  die "STORE called from _check_integrity!" if $DIAGNOSTIC;

  $self-&gt;_fixrecs($rec);

  if ($self-&gt;{autodefer}) {
    $self-&gt;_annotate_ad_history($n);
  }

  return $self-&gt;_store_deferred($n, $rec) if $self-&gt;_is_deferring;


  # We need this to decide whether the new record will fit
  # It incidentally populates the offsets table 
  # Note we have to do this before we alter the cache
  # 20020324 Wait, but this DOES alter the cache.  TODO BUG?
  my $oldrec = $self-&gt;_fetch($n);

  if (not defined $oldrec) {
    # We're storing a record beyond the end of the file
    $self-&gt;_extend_file_to($n+1);
    $oldrec = $self-&gt;{recsep};
  }
#  return if $oldrec eq $rec;    # don't bother
  my $len_diff = length($rec) - length($oldrec);

  # length($oldrec) here is not consistent with text mode  TODO XXX BUG
  $self-&gt;_mtwrite($rec, $self-&gt;{offsets}[$n], length($oldrec));
  $self-&gt;_oadjust([$n, 1, $rec]);
  $self-&gt;{cache}-&gt;update($n, $rec);
}

sub _store_deferred {
  my ($self, $n, $rec) = @_;
  $self-&gt;{cache}-&gt;remove($n);
  my $old_deferred = $self-&gt;{deferred}{$n};

  if (defined $self-&gt;{deferred_max} &amp;&amp; $n &gt; $self-&gt;{deferred_max}) {
    $self-&gt;{deferred_max} = $n;
  }
  $self-&gt;{deferred}{$n} = $rec;

  my $len_diff = length($rec);
  $len_diff -= length($old_deferred) if defined $old_deferred;
  $self-&gt;{deferred_s} += $len_diff;
  $self-&gt;{cache}-&gt;adj_limit(-$len_diff);
  if ($self-&gt;{deferred_s} &gt; $self-&gt;{dw_size}) {
    $self-&gt;_flush;
  } elsif ($self-&gt;_cache_too_full) {
    $self-&gt;_cache_flush;
  }
}

# Remove a single record from the deferred-write buffer without writing it
# The record need not be present
sub _delete_deferred {
  my ($self, $n) = @_;
  my $rec = delete $self-&gt;{deferred}{$n};
  return unless defined $rec;

  if (defined $self-&gt;{deferred_max} 
      &amp;&amp; $n == $self-&gt;{deferred_max}) {
    undef $self-&gt;{deferred_max};
  }

  $self-&gt;{deferred_s} -= length $rec;
  $self-&gt;{cache}-&gt;adj_limit(length $rec);
}

sub FETCHSIZE {
  my $self = shift;
  my $n = $self-&gt;{eof} ? $#{$self-&gt;{offsets}} : $self-&gt;_fill_offsets;

  my $top_deferred = $self-&gt;_defer_max;
  $n = $top_deferred+1 if defined $top_deferred &amp;&amp; $n &lt; $top_deferred+1;
  $n;
}

sub STORESIZE {
  my ($self, $len) = @_;

  if ($self-&gt;{autodefer}) {
    $self-&gt;_annotate_ad_history('STORESIZE');
  }

  my $olen = $self-&gt;FETCHSIZE;
  return if $len == $olen;      # Woo-hoo!

  # file gets longer
  if ($len &gt; $olen) {
    if ($self-&gt;_is_deferring) {
      for ($olen .. $len-1) {
        $self-&gt;_store_deferred($_, $self-&gt;{recsep});
      }
    } else {
      $self-&gt;_extend_file_to($len);
    }
    return;
  }

  # file gets shorter
  if ($self-&gt;_is_deferring) {
    # TODO maybe replace this with map-plus-assignment?
    for (grep $_ &gt;= $len, keys %{$self-&gt;{deferred}}) {
      $self-&gt;_delete_deferred($_);
    }
    $self-&gt;{deferred_max} = $len-1;
  }

  $self-&gt;_seek($len);
  $self-&gt;_chop_file;
  $#{$self-&gt;{offsets}} = $len;
#  $self-&gt;{offsets}[0] = 0;      # in case we just chopped this

  $self-&gt;{cache}-&gt;remove(grep $_ &gt;= $len, $self-&gt;{cache}-&gt;ckeys);
}

### OPTIMIZE ME
### It should not be necessary to do FETCHSIZE
### Just seek to the end of the file.
sub PUSH {
  my $self = shift;
  $self-&gt;SPLICE($self-&gt;FETCHSIZE, scalar(@_), @_);

  # No need to return:
  #  $self-&gt;FETCHSIZE;  # because av.c takes care of this for me
}

sub POP {
  my $self = shift;
  my $size = $self-&gt;FETCHSIZE;
  return if $size == 0;
#  print STDERR "# POPPITY POP POP POP\n";
  scalar $self-&gt;SPLICE($size-1, 1);
}

sub SHIFT {
  my $self = shift;
  scalar $self-&gt;SPLICE(0, 1);
}

sub UNSHIFT {
  my $self = shift;
  $self-&gt;SPLICE(0, 0, @_);
  # $self-&gt;FETCHSIZE; # av.c takes care of this for me
}

sub CLEAR {
  my $self = shift;

  if ($self-&gt;{autodefer}) {
    $self-&gt;_annotate_ad_history('CLEAR');
  }

  $self-&gt;_seekb(0);
  $self-&gt;_chop_file;
    $self-&gt;{cache}-&gt;set_limit($self-&gt;{memory});
    $self-&gt;{cache}-&gt;empty;
  @{$self-&gt;{offsets}} = (0);
  %{$self-&gt;{deferred}}= ();
    $self-&gt;{deferred_s} = 0;
    $self-&gt;{deferred_max} = -1;
}

sub EXTEND {
  my ($self, $n) = @_;

  # No need to pre-extend anything in this case
  return if $self-&gt;_is_deferring;

  $self-&gt;_fill_offsets_to($n);
  $self-&gt;_extend_file_to($n);
}

sub DELETE {
  my ($self, $n) = @_;

  if ($self-&gt;{autodefer}) {
    $self-&gt;_annotate_ad_history('DELETE');
  }

  my $lastrec = $self-&gt;FETCHSIZE-1;
  my $rec = $self-&gt;FETCH($n);
  $self-&gt;_delete_deferred($n) if $self-&gt;_is_deferring;
  if ($n == $lastrec) {
    $self-&gt;_seek($n);
    $self-&gt;_chop_file;
    $#{$self-&gt;{offsets}}--;
    $self-&gt;{cache}-&gt;remove($n);
    # perhaps in this case I should also remove trailing null records?
    # 20020316
    # Note that delete @a[-3..-1] deletes the records in the wrong order,
    # so we only chop the very last one out of the file.  We could repair this
    # by tracking deleted records inside the object.
  } elsif ($n &lt; $lastrec) {
    $self-&gt;STORE($n, "");
  }
  $rec;
}

sub EXISTS {
  my ($self, $n) = @_;
  return 1 if exists $self-&gt;{deferred}{$n};
  $n &lt; $self-&gt;FETCHSIZE;
}

sub SPLICE {
  my $self = shift;

  if ($self-&gt;{autodefer}) {
    $self-&gt;_annotate_ad_history('SPLICE');
  }

  $self-&gt;_flush if $self-&gt;_is_deferring; # move this up?
  if (wantarray) {
    $self-&gt;_chomp(my @a = $self-&gt;_splice(@_));
    @a;
  } else {
    $self-&gt;_chomp1(scalar $self-&gt;_splice(@_));
  }
}

sub DESTROY {
  my $self = shift;
  $self-&gt;flush if $self-&gt;_is_deferring;
  $self-&gt;{cache}-&gt;delink if defined $self-&gt;{cache}; # break circular link
  if ($self-&gt;{fh} and $self-&gt;{ourfh}) {
      delete $self-&gt;{ourfh};
      close delete $self-&gt;{fh};
  }
}

sub _splice {
  my ($self, $pos, $nrecs, @data) = @_;
  my @result;

  $pos = 0 unless defined $pos;

  # Deal with negative and other out-of-range positions
  # Also set default for $nrecs 
  {
    my $oldsize = $self-&gt;FETCHSIZE;
    $nrecs = $oldsize unless defined $nrecs;
    my $oldpos = $pos;

    if ($pos &lt; 0) {
      $pos += $oldsize;
      if ($pos &lt; 0) {
        croak "Modification of non-creatable array value attempted, " .
              "subscript $oldpos";
      }
    }

    if ($pos &gt; $oldsize) {
      return unless @data;
      $pos = $oldsize;          # This is what perl does for normal arrays
    }

    # The manual is very unclear here
    if ($nrecs &lt; 0) {
      $nrecs = $oldsize - $pos + $nrecs;
      $nrecs = 0 if $nrecs &lt; 0;
    }

    # nrecs is too big---it really means "until the end"
    # 20030507
    if ($nrecs + $pos &gt; $oldsize) {
      $nrecs = $oldsize - $pos;
    }
  }

  $self-&gt;_fixrecs(@data);
  my $data = join '', @data;
  my $datalen = length $data;
  my $oldlen = 0;

  # compute length of data being removed
  for ($pos .. $pos+$nrecs-1) {
    last unless defined $self-&gt;_fill_offsets_to($_);
    my $rec = $self-&gt;_fetch($_);
    last unless defined $rec;
    push @result, $rec;

    # Why don't we just use length($rec) here?
    # Because that record might have come from the cache.  _splice
    # might have been called to flush out the deferred-write records,
    # and in this case length($rec) is the length of the record to be
    # *written*, not the length of the actual record in the file.  But
    # the offsets are still true. 20020322
    $oldlen += $self-&gt;{offsets}[$_+1] - $self-&gt;{offsets}[$_]
      if defined $self-&gt;{offsets}[$_+1];
  }
  $self-&gt;_fill_offsets_to($pos+$nrecs);

  # Modify the file
  $self-&gt;_mtwrite($data, $self-&gt;{offsets}[$pos], $oldlen);
  # Adjust the offsets table
  $self-&gt;_oadjust([$pos, $nrecs, @data]);

  { # Take this read cache stuff out into a separate function
    # You made a half-attempt to put it into _oadjust.  
    # Finish something like that up eventually.
    # STORE also needs to do something similarish

    # update the read cache, part 1
    # modified records
    for ($pos .. $pos+$nrecs-1) {
      my $new = $data[$_-$pos];
      if (defined $new) {
        $self-&gt;{cache}-&gt;update($_, $new);
      } else {
        $self-&gt;{cache}-&gt;remove($_);
      }
    }
    
    # update the read cache, part 2
    # moved records - records past the site of the change
    # need to be renumbered
    # Maybe merge this with the previous block?
    {
      my @oldkeys = grep $_ &gt;= $pos + $nrecs, $self-&gt;{cache}-&gt;ckeys;
      my @newkeys = map $_-$nrecs+@data, @oldkeys;
      $self-&gt;{cache}-&gt;rekey(\@oldkeys, \@newkeys);
    }

    # Now there might be too much data in the cache, if we spliced out
    # some short records and spliced in some long ones.  If so, flush
    # the cache.
    $self-&gt;_cache_flush;
  }

  # Yes, the return value of 'splice' *is* actually this complicated
  wantarray ? @result : @result ? $result[-1] : undef;
}


# write data into the file
# $data is the data to be written.
# it should be written at position $pos, and should overwrite
# exactly $len of the following bytes.  
# Note that if length($data) &gt; $len, the subsequent bytes will have to 
# be moved up, and if length($data) &lt; $len, they will have to
# be moved down
sub _twrite {
  my ($self, $data, $pos, $len) = @_;

  unless (defined $pos) {
    die "\$pos was undefined in _twrite";
  }

  my $len_diff = length($data) - $len;

  if ($len_diff == 0) {          # Woo-hoo!
    my $fh = $self-&gt;{fh};
    $self-&gt;_seekb($pos);
    $self-&gt;_write_record($data);
    return;                     # well, that was easy.
  }

  # the two records are of different lengths
  # our strategy here: rewrite the tail of the file,
  # reading ahead one buffer at a time
  # $bufsize is required to be at least as large as the data we're overwriting
  my $bufsize = _bufsize($len_diff);
  my ($writepos, $readpos) = ($pos, $pos+$len);
  my $next_block;
  my $more_data;

  # Seems like there ought to be a way to avoid the repeated code
  # and the special case here.  The read(1) is also a little weird.
  # Think about this.
  do {
    $self-&gt;_seekb($readpos);
    my $br = read $self-&gt;{fh}, $next_block, $bufsize;
    $more_data = read $self-&gt;{fh}, my($dummy), 1;
    $self-&gt;_seekb($writepos);
    $self-&gt;_write_record($data);
    $readpos += $br;
    $writepos += length $data;
    $data = $next_block;
  } while $more_data;
  $self-&gt;_seekb($writepos);
  $self-&gt;_write_record($next_block);

  # There might be leftover data at the end of the file
  $self-&gt;_chop_file if $len_diff &lt; 0;
}

# _iwrite(D, S, E)
# Insert text D at position S.
# Let C = E-S-|D|.  If C &lt; 0; die.  
# Data in [S,S+C) is copied to [S+D,S+D+C) = [S+D,E).
# Data in [S+C = E-D, E) is returned.  Data in [E, oo) is untouched.
#
# In a later version, don't read the entire intervening area into
# memory at once; do the copying block by block.
sub _iwrite {
  my $self = shift;
  my ($D, $s, $e) = @_;
  my $d = length $D;
  my $c = $e-$s-$d;
  local *FH = $self-&gt;{fh};
  confess "Not enough space to insert $d bytes between $s and $e"
    if $c &lt; 0;
  confess "[$s,$e) is an invalid insertion range" if $e &lt; $s;

  $self-&gt;_seekb($s);
  read FH, my $buf, $e-$s;

  $D .= substr($buf, 0, $c, "");

  $self-&gt;_seekb($s);
  $self-&gt;_write_record($D);

  return $buf;
}

# Like _twrite, but the data-pos-len triple may be repeated; you may
# write several chunks.  All the writing will be done in
# one pass.   Chunks SHALL be in ascending order and SHALL NOT overlap.
sub _mtwrite {
  my $self = shift;
  my $unwritten = "";
  my $delta = 0;

  @_ % 3 == 0 
    or die "Arguments to _mtwrite did not come in groups of three";

  while (@_) {
    my ($data, $pos, $len) = splice @_, 0, 3;
    my $end = $pos + $len;  # The OLD end of the segment to be replaced
    $data = $unwritten . $data;
    $delta -= length($unwritten);
    $unwritten  = "";
    $pos += $delta;             # This is where the data goes now
    my $dlen = length $data;
    $self-&gt;_seekb($pos);
    if ($len &gt;= $dlen) {        # the data will fit
      $self-&gt;_write_record($data);
      $delta += ($dlen - $len); # everything following moves down by this much
      $data = ""; # All the data in the buffer has been written
    } else {                    # won't fit
      my $writable = substr($data, 0, $len - $delta, "");
      $self-&gt;_write_record($writable);
      $delta += ($dlen - $len); # everything following moves down by this much
    } 

    # At this point we've written some but maybe not all of the data.
    # There might be a gap to close up, or $data might still contain a
    # bunch of unwritten data that didn't fit.
    my $ndlen = length $data;
    if ($delta == 0) {
      $self-&gt;_write_record($data);
    } elsif ($delta &lt; 0) {
      # upcopy (close up gap)
      if (@_) {
        $self-&gt;_upcopy($end, $end + $delta, $_[1] - $end);  
      } else {
        $self-&gt;_upcopy($end, $end + $delta);  
      }
    } else {
      # downcopy (insert data that didn't fit; replace this data in memory
      # with _later_ data that doesn't fit)
      if (@_) {
        $unwritten = $self-&gt;_downcopy($data, $end, $_[1] - $end);
      } else {
        # Make the file longer to accommodate the last segment that doesn't
        $unwritten = $self-&gt;_downcopy($data, $end);
      }
    }
  }
}

# Copy block of data of length $len from position $spos to position $dpos
# $dpos must be &lt;= $spos
#
# If $len is undefined, go all the way to the end of the file
# and then truncate it ($spos - $dpos bytes will be removed)
sub _upcopy {
  my $blocksize = 8192;
  my ($self, $spos, $dpos, $len) = @_;
  if ($dpos &gt; $spos) {
    die "source ($spos) was upstream of destination ($dpos) in _upcopy";
  } elsif ($dpos == $spos) {
    return;
  }

  while (! defined ($len) || $len &gt; 0) {
    my $readsize = ! defined($len) ? $blocksize
               : $len &gt; $blocksize ? $blocksize
               : $len;
      
    my $fh = $self-&gt;{fh};
    $self-&gt;_seekb($spos);
    my $bytes_read = read $fh, my($data), $readsize;
    $self-&gt;_seekb($dpos);
    if ($data eq "") { 
      $self-&gt;_chop_file;
      last;
    }
    $self-&gt;_write_record($data);
    $spos += $bytes_read;
    $dpos += $bytes_read;
    $len -= $bytes_read if defined $len;
  }
}

# Write $data into a block of length $len at position $pos,
# moving everything in the block forwards to make room.
# Instead of writing the last length($data) bytes from the block
# (because there isn't room for them any longer) return them.
#
# Undefined $len means 'until the end of the file'
sub _downcopy {
  my $blocksize = 8192;
  my ($self, $data, $pos, $len) = @_;
  my $fh = $self-&gt;{fh};

  while (! defined $len || $len &gt; 0) {
    my $readsize = ! defined($len) ? $blocksize 
      : $len &gt; $blocksize? $blocksize : $len;
    $self-&gt;_seekb($pos);
    read $fh, my($old), $readsize;
    my $last_read_was_short = length($old) &lt; $readsize;
    $data .= $old;
    my $writable;
    if ($last_read_was_short) {
      # If last read was short, then $data now contains the entire rest
      # of the file, so there's no need to write only one block of it
      $writable = $data;
      $data = "";
    } else {
      $writable = substr($data, 0, $readsize, "");
    }
    last if $writable eq "";
    $self-&gt;_seekb($pos);
    $self-&gt;_write_record($writable);
    last if $last_read_was_short &amp;&amp; $data eq "";
    $len -= $readsize if defined $len;
    $pos += $readsize;
  }
  return $data;
}

# Adjust the object data structures following an '_mtwrite'
# Arguments are
#  [$pos, $nrecs, @length]  items
# indicating that $nrecs records were removed at $recpos (a record offset)
# and replaced with records of length @length...
# Arguments guarantee that $recpos is strictly increasing.
# No return value
sub _oadjust {
  my $self = shift;
  my $delta = 0;
  my $delta_recs = 0;
  my $prev_end = -1;
  my %newkeys;

  for (@_) {
    my ($pos, $nrecs, @data) = @$_;
    $pos += $delta_recs;

    # Adjust the offsets of the records after the previous batch up
    # to the first new one of this batch
    for my $i ($prev_end+2 .. $pos - 1) {
      $self-&gt;{offsets}[$i] += $delta;
      $newkey{$i} = $i + $delta_recs;
    }

    $prev_end = $pos + @data - 1; # last record moved on this pass 

    # Remove the offsets for the removed records;
    # replace with the offsets for the inserted records
    my @newoff = ($self-&gt;{offsets}[$pos] + $delta);
    for my $i (0 .. $#data) {
      my $newlen = length $data[$i];
      push @newoff, $newoff[$i] + $newlen;
      $delta += $newlen;
    }

    for my $i ($pos .. $pos+$nrecs-1) {
      last if $i+1 &gt; $#{$self-&gt;{offsets}};
      my $oldlen = $self-&gt;{offsets}[$i+1] - $self-&gt;{offsets}[$i];
      $delta -= $oldlen;
    }

#    # also this data has changed, so update it in the cache
#    for (0 .. $#data) {
#      $self-&gt;{cache}-&gt;update($pos + $_, $data[$_]);
#    }
#    if ($delta_recs) {
#      my @oldkeys = grep $_ &gt;= $pos + @data, $self-&gt;{cache}-&gt;ckeys;
#      my @newkeys = map $_ + $delta_recs, @oldkeys;
#      $self-&gt;{cache}-&gt;rekey(\@oldkeys, \@newkeys);
#    }

    # replace old offsets with new
    splice @{$self-&gt;{offsets}}, $pos, $nrecs+1, @newoff;
    # What if we just spliced out the end of the offsets table?
    # shouldn't we clear $self-&gt;{eof}?   Test for this XXX BUG TODO

    $delta_recs += @data - $nrecs; # net change in total number of records
  }

  # The trailing records at the very end of the file
  if ($delta) {
    for my $i ($prev_end+2 .. $#{$self-&gt;{offsets}}) {
      $self-&gt;{offsets}[$i] += $delta;
    }
  }

  # If we scrubbed out all known offsets, regenerate the trivial table
  # that knows that the file does indeed start at 0.
  $self-&gt;{offsets}[0] = 0 unless @{$self-&gt;{offsets}};
  # If the file got longer, the offsets table is no longer complete
  # $self-&gt;{eof} = 0 if $delta_recs &gt; 0;

  # Now there might be too much data in the cache, if we spliced out
  # some short records and spliced in some long ones.  If so, flush
  # the cache.
  $self-&gt;_cache_flush;
}

# If a record does not already end with the appropriate terminator
# string, append one.
sub _fixrecs {
  my $self = shift;
  for (@_) {
    $_ = "" unless defined $_;
    $_ .= $self-&gt;{recsep}
      unless substr($_, - $self-&gt;{recseplen}) eq $self-&gt;{recsep};
  }
}


################################################################
#
# Basic read, write, and seek
#

# seek to the beginning of record #$n
# Assumes that the offsets table is already correctly populated
#
# Note that $n=-1 has a special meaning here: It means the start of
# the last known record; this may or may not be the very last record
# in the file, depending on whether the offsets table is fully populated.
#
sub _seek {
  my ($self, $n) = @_;
  my $o = $self-&gt;{offsets}[$n];
  defined($o)
    or confess("logic error: undefined offset for record $n");
  seek $self-&gt;{fh}, $o, SEEK_SET
    or confess "Couldn't seek filehandle: $!";  # "Should never happen."
}

# seek to byte $b in the file
sub _seekb {
  my ($self, $b) = @_;
  seek $self-&gt;{fh}, $b, SEEK_SET
    or die "Couldn't seek filehandle: $!";  # "Should never happen."
}

# populate the offsets table up to the beginning of record $n
# return the offset of record $n
sub _fill_offsets_to {
  my ($self, $n) = @_;

  return $self-&gt;{offsets}[$n] if $self-&gt;{eof};

  my $fh = $self-&gt;{fh};
  local *OFF = $self-&gt;{offsets};
  my $rec;

  until ($#OFF &gt;= $n) {
    $self-&gt;_seek(-1);           # tricky -- see comment at _seek
    $rec = $self-&gt;_read_record;
    if (defined $rec) {
      push @OFF, int(tell $fh);  # Tels says that int() saves memory here
    } else {
      $self-&gt;{eof} = 1;
      return;                   # It turns out there is no such record
    }
  }

  # we have now read all the records up to record n-1,
  # so we can return the offset of record n
  $OFF[$n];
}

sub _fill_offsets {
  my ($self) = @_;

  my $fh = $self-&gt;{fh};
  local *OFF = $self-&gt;{offsets};

  $self-&gt;_seek(-1);           # tricky -- see comment at _seek

  # Tels says that inlining read_record() would make this loop
  # five times faster. 20030508
  while ( defined $self-&gt;_read_record()) {
    # int() saves us memory here
    push @OFF, int(tell $fh);
  }

  $self-&gt;{eof} = 1;
  $#OFF;
}

# assumes that $rec is already suitably terminated
sub _write_record {
  my ($self, $rec) = @_;
  my $fh = $self-&gt;{fh};
  local $\ = "";
  print $fh $rec
    or die "Couldn't write record: $!";  # "Should never happen."
#  $self-&gt;{_written} += length($rec);
}

sub _read_record {
  my $self = shift;
  my $rec;
  { local $/ = $self-&gt;{recsep};
    my $fh = $self-&gt;{fh};
    $rec = &lt;$fh&gt;;
  }
  return unless defined $rec;
  if (substr($rec, -$self-&gt;{recseplen}) ne $self-&gt;{recsep}) {
    # improperly terminated final record --- quietly fix it.
#    my $ac = substr($rec, -$self-&gt;{recseplen});
#    $ac =~ s/\n/\\n/g;
    $self-&gt;{sawlastrec} = 1;
    unless ($self-&gt;{rdonly}) {
      local $\ = "";
      my $fh = $self-&gt;{fh};
      print $fh $self-&gt;{recsep};
    }
    $rec .= $self-&gt;{recsep};
  }
#  $self-&gt;{_read} += length($rec) if defined $rec;
  $rec;
}

sub _rw_stats {
  my $self = shift;
  @{$self}{'_read', '_written'};
}

################################################################
#
# Read cache management

sub _cache_flush {
  my ($self) = @_;
  $self-&gt;{cache}-&gt;reduce_size_to($self-&gt;{memory} - $self-&gt;{deferred_s});
}

sub _cache_too_full {
  my $self = shift;
  $self-&gt;{cache}-&gt;bytes + $self-&gt;{deferred_s} &gt;= $self-&gt;{memory};
}

################################################################
#
# File custodial services
#


# We have read to the end of the file and have the offsets table
# entirely populated.  Now we need to write a new record beyond
# the end of the file.  We prepare for this by writing
# empty records into the file up to the position we want
#
# assumes that the offsets table already contains the offset of record $n,
# if it exists, and extends to the end of the file if not.
sub _extend_file_to {
  my ($self, $n) = @_;
  $self-&gt;_seek(-1);             # position after the end of the last record
  my $pos = $self-&gt;{offsets}[-1];

  # the offsets table has one entry more than the total number of records
  my $extras = $n - $#{$self-&gt;{offsets}};

  # Todo : just use $self-&gt;{recsep} x $extras here?
  while ($extras-- &gt; 0) {
    $self-&gt;_write_record($self-&gt;{recsep});
    push @{$self-&gt;{offsets}}, int(tell $self-&gt;{fh});
  }
}

# Truncate the file at the current position
sub _chop_file {
  my $self = shift;
  truncate $self-&gt;{fh}, tell($self-&gt;{fh});
}


# compute the size of a buffer suitable for moving
# all the data in a file forward $n bytes
# ($n may be negative)
# The result should be at least $n.
sub _bufsize {
  my $n = shift;
  return 8192 if $n &lt;= 0;
  my $b = $n &amp; ~8191;
  $b += 8192 if $n &amp; 8191;
  $b;
}

################################################################
#
# Miscellaneous public methods
#

# Lock the file
sub flock {
  my ($self, $op) = @_;
  unless (@_ &lt;= 3) {
    my $pack = ref $self;
    croak "Usage: $pack\-&gt;flock([OPERATION])";
  }
  my $fh = $self-&gt;{fh};
  $op = LOCK_EX unless defined $op;
  my $locked = flock $fh, $op;

  if ($locked &amp;&amp; ($op &amp; (LOCK_EX | LOCK_SH))) {
    # If you're locking the file, then presumably it's because
    # there might have been a write access by another process.
    # In that case, the read cache contents and the offsets table
    # might be invalid, so discard them.  20030508
    $self-&gt;{offsets} = [0];
    $self-&gt;{cache}-&gt;empty;
  }

  $locked;
}

# Get/set autochomp option
sub autochomp {
  my $self = shift;
  if (@_) {
    my $old = $self-&gt;{autochomp};
    $self-&gt;{autochomp} = shift;
    $old;
  } else {
    $self-&gt;{autochomp};
  }
}

# Get offset table entries; returns offset of nth record
sub offset {
  my ($self, $n) = @_;

  if ($#{$self-&gt;{offsets}} &lt; $n) {
    return if $self-&gt;{eof};     # request for record beyond the end of file
    my $o = $self-&gt;_fill_offsets_to($n);
    # If it's still undefined, there is no such record, so return 'undef'
    return unless defined $o;
   }

  $self-&gt;{offsets}[$n];
}

sub discard_offsets {
  my $self = shift;
  $self-&gt;{offsets} = [0];
}

################################################################
#
# Matters related to deferred writing
#

# Defer writes
sub defer {
  my $self = shift;
  $self-&gt;_stop_autodeferring;
  @{$self-&gt;{ad_history}} = ();
  $self-&gt;{defer} = 1;
}

# Flush deferred writes
#
# This could be better optimized to write the file in one pass, instead
# of one pass per block of records.  But that will require modifications
# to _twrite, so I should have a good _twrite test suite first.
sub flush {
  my $self = shift;

  $self-&gt;_flush;
  $self-&gt;{defer} = 0;
}

sub _old_flush {
  my $self = shift;
  my @writable = sort {$a&lt;=&gt;$b} (keys %{$self-&gt;{deferred}});

  while (@writable) {
    # gather all consecutive records from the front of @writable
    my $first_rec = shift @writable;
    my $last_rec = $first_rec+1;
    ++$last_rec, shift @writable while @writable &amp;&amp; $last_rec == $writable[0];
    --$last_rec;
    $self-&gt;_fill_offsets_to($last_rec);
    $self-&gt;_extend_file_to($last_rec);
    $self-&gt;_splice($first_rec, $last_rec-$first_rec+1, 
                   @{$self-&gt;{deferred}}{$first_rec .. $last_rec});
  }

  $self-&gt;_discard;               # clear out defered-write-cache
}

sub _flush {
  my $self = shift;
  my @writable = sort {$a&lt;=&gt;$b} (keys %{$self-&gt;{deferred}});
  my @args;
  my @adjust;

  while (@writable) {
    # gather all consecutive records from the front of @writable
    my $first_rec = shift @writable;
    my $last_rec = $first_rec+1;
    ++$last_rec, shift @writable while @writable &amp;&amp; $last_rec == $writable[0];
    --$last_rec;
    my $end = $self-&gt;_fill_offsets_to($last_rec+1);
    if (not defined $end) {
      $self-&gt;_extend_file_to($last_rec);
      $end = $self-&gt;{offsets}[$last_rec];
    }
    my ($start) = $self-&gt;{offsets}[$first_rec];
    push @args,
         join("", @{$self-&gt;{deferred}}{$first_rec .. $last_rec}), # data
         $start,                                                  # position
         $end-$start;                                             # length
    push @adjust, [$first_rec, # starting at this position...
                   $last_rec-$first_rec+1,  # this many records...
                   # are replaced with these...
                   @{$self-&gt;{deferred}}{$first_rec .. $last_rec},
                  ];
  }

  $self-&gt;_mtwrite(@args);  # write multiple record groups
  $self-&gt;_discard;               # clear out defered-write-cache
  $self-&gt;_oadjust(@adjust);
}

# Discard deferred writes and disable future deferred writes
sub discard {
  my $self = shift;
  $self-&gt;_discard;
  $self-&gt;{defer} = 0;
}

# Discard deferred writes, but retain old deferred writing mode
sub _discard {
  my $self = shift;
  %{$self-&gt;{deferred}} = ();
  $self-&gt;{deferred_s}  = 0;
  $self-&gt;{deferred_max}  = -1;
  $self-&gt;{cache}-&gt;set_limit($self-&gt;{memory});
}

# Deferred writing is enabled, either explicitly ($self-&gt;{defer})
# or automatically ($self-&gt;{autodeferring})
sub _is_deferring {
  my $self = shift;
  $self-&gt;{defer} || $self-&gt;{autodeferring};
}

# The largest record number of any deferred record
sub _defer_max {
  my $self = shift;
  return $self-&gt;{deferred_max} if defined $self-&gt;{deferred_max};
  my $max = -1;
  for my $key (keys %{$self-&gt;{deferred}}) {
    $max = $key if $key &gt; $max;
  }
  $self-&gt;{deferred_max} = $max;
  $max;
}

################################################################
#
# Matters related to autodeferment
#

# Get/set autodefer option
sub autodefer {
  my $self = shift;
  if (@_) {
    my $old = $self-&gt;{autodefer};
    $self-&gt;{autodefer} = shift;
    if ($old) {
      $self-&gt;_stop_autodeferring;
      @{$self-&gt;{ad_history}} = ();
    }
    $old;
  } else {
    $self-&gt;{autodefer};
  }
}

# The user is trying to store record #$n Record that in the history,
# and then enable (or disable) autodeferment if that seems useful.
# Note that it's OK for $n to be a non-number, as long as the function
# is prepared to deal with that.  Nobody else looks at the ad_history.
#
# Now, what does the ad_history mean, and what is this function doing?
# Essentially, the idea is to enable autodeferring when we see that the
# user has made three consecutive STORE calls to three consecutive records.
# ("Three" is actually -&gt;{autodefer_threshhold}.)
# A STORE call for record #$n inserts $n into the autodefer history,
# and if the history contains three consecutive records, we enable 
# autodeferment.  An ad_history of [X, Y] means that the most recent
# STOREs were for records X, X+1, ..., Y, in that order.  
#
# Inserting a nonconsecutive number erases the history and starts over.
#
# Performing a special operation like SPLICE erases the history.
#
# There's one special case: CLEAR means that CLEAR was just called.
# In this case, we prime the history with [-2, -1] so that if the next
# write is for record 0, autodeferring goes on immediately.  This is for
# the common special case of "@a = (...)".
#
sub _annotate_ad_history {
  my ($self, $n) = @_;
  return unless $self-&gt;{autodefer}; # feature is disabled
  return if $self-&gt;{defer};     # already in explicit defer mode
  return unless $self-&gt;{offsets}[-1] &gt;= $self-&gt;{autodefer_filelen_threshhold};

  local *H = $self-&gt;{ad_history};
  if ($n eq 'CLEAR') {
    @H = (-2, -1);              # prime the history with fake records
    $self-&gt;_stop_autodeferring;
  } elsif ($n =~ /^\d+$/) {
    if (@H == 0) {
      @H =  ($n, $n);
    } else {                    # @H == 2
      if ($H[1] == $n-1) {      # another consecutive record
        $H[1]++;
        if ($H[1] - $H[0] + 1 &gt;= $self-&gt;{autodefer_threshhold}) {
          $self-&gt;{autodeferring} = 1;
        }
      } else {                  # nonconsecutive- erase and start over
        @H = ($n, $n);
        $self-&gt;_stop_autodeferring;
      }
    }
  } else {                      # SPLICE or STORESIZE or some such
    @H = ();
    $self-&gt;_stop_autodeferring;
  }
}

# If autodeferring was enabled, cut it out and discard the history
sub _stop_autodeferring {
  my $self = shift;
  if ($self-&gt;{autodeferring}) {
    $self-&gt;_flush;
  }
  $self-&gt;{autodeferring} = 0;
}

################################################################


# This is NOT a method.  It is here for two reasons:
#  1. To factor a fairly complicated block out of the constructor
#  2. To provide access for the test suite, which need to be sure
#     files are being written properly.
sub _default_recsep {
  my $recsep = $/;
  if ($^O eq 'MSWin32') {       # Dos too?
    # Windows users expect files to be terminated with \r\n
    # But $/ is set to \n instead
    # Note that this also transforms \n\n into \r\n\r\n.
    # That is a feature.
    $recsep =~ s/\n/\r\n/g;
  }
  $recsep;
}

# Utility function for _check_integrity
sub _ci_warn {
  my $msg = shift;
  $msg =~ s/\n/\\n/g;
  $msg =~ s/\r/\\r/g;
  print "# $msg\n";
}

# Given a file, make sure the cache is consistent with the
# file contents and the internal data structures are consistent with
# each other.  Returns true if everything checks out, false if not
#
# The $file argument is no longer used.  It is retained for compatibility
# with the existing test suite.
sub _check_integrity {
  my ($self, $file, $warn) = @_;
  my $rsl = $self-&gt;{recseplen};
  my $rs  = $self-&gt;{recsep};
  my $good = 1; 
  local *_;                     # local $_ does not work here
  local $DIAGNOSTIC = 1;

  if (not defined $rs) {
    _ci_warn("recsep is undef!");
    $good = 0;
  } elsif ($rs eq "") {
    _ci_warn("recsep is empty!");
    $good = 0;
  } elsif ($rsl != length $rs) {
    my $ln = length $rs;
    _ci_warn("recsep &lt;$rs&gt; has length $ln, should be $rsl");
    $good = 0;
  }

  if (not defined $self-&gt;{offsets}[0]) {
    _ci_warn("offset 0 is missing!");
    $good = 0;

  } elsif ($self-&gt;{offsets}[0] != 0) {
    _ci_warn("rec 0: offset &lt;$self-&gt;{offsets}[0]&gt; s/b 0!");
    $good = 0;
  }

  my $cached = 0;
  {
    local *F = $self-&gt;{fh};
    seek F, 0, SEEK_SET;
    local $. = 0;
    local $/ = $rs;

    while (&lt;F&gt;) {
      my $n = $. - 1;
      my $cached = $self-&gt;{cache}-&gt;_produce($n);
      my $offset = $self-&gt;{offsets}[$.];
      my $ao = tell F;
      if (defined $offset &amp;&amp; $offset != $ao) {
        _ci_warn("rec $n: offset &lt;$offset&gt; actual &lt;$ao&gt;");
        $good = 0;
      }
      if (defined $cached &amp;&amp; $_ ne $cached &amp;&amp; ! $self-&gt;{deferred}{$n}) {
        $good = 0;
        _ci_warn("rec $n: cached &lt;$cached&gt; actual &lt;$_&gt;");
      }
      if (defined $cached &amp;&amp; substr($cached, -$rsl) ne $rs) {
        $good = 0;
        _ci_warn("rec $n in the cache is missing the record separator");
      }
      if (! defined $offset &amp;&amp; $self-&gt;{eof}) {
        $good = 0;
        _ci_warn("The offset table was marked complete, but it is missing " .
                 "element $.");
      }
    }
    if (@{$self-&gt;{offsets}} &gt; $.+1) {
        $good = 0;
        my $n = @{$self-&gt;{offsets}};
        _ci_warn("The offset table has $n items, but the file has only $.");
    }

    my $deferring = $self-&gt;_is_deferring;
    for my $n ($self-&gt;{cache}-&gt;ckeys) {
      my $r = $self-&gt;{cache}-&gt;_produce($n);
      $cached += length($r);
      next if $n+1 &lt;= $.;         # checked this already
      _ci_warn("spurious caching of record $n");
      $good = 0;
    }
    my $b = $self-&gt;{cache}-&gt;bytes;
    if ($cached != $b) {
      _ci_warn("cache size is $b, should be $cached");
      $good = 0;
    }
  }

  # That cache has its own set of tests
  $good = 0 unless $self-&gt;{cache}-&gt;_check_integrity;

  # Now let's check the deferbuffer
  # Unless deferred writing is enabled, it should be empty
  if (! $self-&gt;_is_deferring &amp;&amp; %{$self-&gt;{deferred}}) {
    _ci_warn("deferred writing disabled, but deferbuffer nonempty");
    $good = 0;
  }

  # Any record in the deferbuffer should *not* be present in the readcache
  my $deferred_s = 0;
  while (my ($n, $r) = each %{$self-&gt;{deferred}}) {
    $deferred_s += length($r);
    if (defined $self-&gt;{cache}-&gt;_produce($n)) {
      _ci_warn("record $n is in the deferbuffer *and* the readcache");
      $good = 0;
    }
    if (substr($r, -$rsl) ne $rs) {
      _ci_warn("rec $n in the deferbuffer is missing the record separator");
      $good = 0;
    }
  }

  # Total size of deferbuffer should match internal total
  if ($deferred_s != $self-&gt;{deferred_s}) {
    _ci_warn("buffer size is $self-&gt;{deferred_s}, should be $deferred_s");
    $good = 0;
  }

  # Total size of deferbuffer should not exceed the specified limit
  if ($deferred_s &gt; $self-&gt;{dw_size}) {
    _ci_warn("buffer size is $self-&gt;{deferred_s} which exceeds the limit " .
             "of $self-&gt;{dw_size}");
    $good = 0;
  }

  # Total size of cached data should not exceed the specified limit
  if ($deferred_s + $cached &gt; $self-&gt;{memory}) {
    my $total = $deferred_s + $cached;
    _ci_warn("total stored data size is $total which exceeds the limit " .
             "of $self-&gt;{memory}");
    $good = 0;
  }

  # Stuff related to autodeferment
  if (!$self-&gt;{autodefer} &amp;&amp; @{$self-&gt;{ad_history}}) {
    _ci_warn("autodefer is disabled, but ad_history is nonempty");
    $good = 0;
  }
  if ($self-&gt;{autodeferring} &amp;&amp; $self-&gt;{defer}) {
    _ci_warn("both autodeferring and explicit deferring are active");
    $good = 0;
  }
  if (@{$self-&gt;{ad_history}} == 0) {
    # That's OK, no additional tests required
  } elsif (@{$self-&gt;{ad_history}} == 2) {
    my @non_number = grep !/^-?\d+$/, @{$self-&gt;{ad_history}};
    if (@non_number) {
      my $msg;
      { local $" = ')(';
        $msg = "ad_history contains non-numbers (@{$self-&gt;{ad_history}})";
      }
      _ci_warn($msg);
      $good = 0;
    } elsif ($self-&gt;{ad_history}[1] &lt; $self-&gt;{ad_history}[0]) {
      _ci_warn("ad_history has nonsensical values @{$self-&gt;{ad_history}}");
      $good = 0;
    }
  } else {
    _ci_warn("ad_history has bad length &lt;@{$self-&gt;{ad_history}}&gt;");
    $good = 0;
  }

  $good;
}

################################################################
#
# Tie::File::Cache
#
# Read cache

package Tie::File::Cache;
$Tie::File::Cache::VERSION = $Tie::File::VERSION;
use Carp ':DEFAULT', 'confess';

sub HEAP () { 0 }
sub HASH () { 1 }
sub MAX  () { 2 }
sub BYTES() { 3 }
#sub STAT () { 4 } # Array with request statistics for each record
#sub MISS () { 5 } # Total number of cache misses
#sub REQ  () { 6 } # Total number of cache requests 
use strict 'vars';

sub new {
  my ($pack, $max) = @_;
  local *_;
  croak "missing argument to -&gt;new" unless defined $max;
  my $self = [];
  bless $self =&gt; $pack;
  @$self = (Tie::File::Heap-&gt;new($self), {}, $max, 0);
  $self;
}

sub adj_limit {
  my ($self, $n) = @_;
  $self-&gt;[MAX] += $n;
}

sub set_limit {
  my ($self, $n) = @_;
  $self-&gt;[MAX] = $n;
}

# For internal use only
# Will be called by the heap structure to notify us that a certain 
# piece of data has moved from one heap element to another.
# $k is the hash key of the item
# $n is the new index into the heap at which it is stored
# If $n is undefined, the item has been removed from the heap.
sub _heap_move {
  my ($self, $k, $n) = @_;
  if (defined $n) {
    $self-&gt;[HASH]{$k} = $n;
  } else {
    delete $self-&gt;[HASH]{$k};
  }
}

sub insert {
  my ($self, $key, $val) = @_;
  local *_;
  croak "missing argument to -&gt;insert" unless defined $key;
  unless (defined $self-&gt;[MAX]) {
    confess "undefined max" ;
  }
  confess "undefined val" unless defined $val;
  return if length($val) &gt; $self-&gt;[MAX];

#  if ($self-&gt;[STAT]) {
#    $self-&gt;[STAT][$key] = 1;
#    return;
#  }

  my $oldnode = $self-&gt;[HASH]{$key};
  if (defined $oldnode) {
    my $oldval = $self-&gt;[HEAP]-&gt;set_val($oldnode, $val);
    $self-&gt;[BYTES] -= length($oldval);
  } else {
    $self-&gt;[HEAP]-&gt;insert($key, $val);
  }
  $self-&gt;[BYTES] += length($val);
  $self-&gt;flush if $self-&gt;[BYTES] &gt; $self-&gt;[MAX];
}

sub expire {
  my $self = shift;
  my $old_data = $self-&gt;[HEAP]-&gt;popheap;
  return unless defined $old_data;
  $self-&gt;[BYTES] -= length $old_data;
  $old_data;
}

sub remove {
  my ($self, @keys) = @_;
  my @result;

#  if ($self-&gt;[STAT]) {
#    for my $key (@keys) {
#      $self-&gt;[STAT][$key] = 0;
#    }
#    return;
#  }

  for my $key (@keys) {
    next unless exists $self-&gt;[HASH]{$key};
    my $old_data = $self-&gt;[HEAP]-&gt;remove($self-&gt;[HASH]{$key});
    $self-&gt;[BYTES] -= length $old_data;
    push @result, $old_data;
  }
  @result;
}

sub lookup {
  my ($self, $key) = @_;
  local *_;
  croak "missing argument to -&gt;lookup" unless defined $key;

#  if ($self-&gt;[STAT]) {
#    $self-&gt;[MISS]++  if $self-&gt;[STAT][$key]++ == 0;
#    $self-&gt;[REQ]++;
#    my $hit_rate = 1 - $self-&gt;[MISS] / $self-&gt;[REQ];
#    # Do some testing to determine this threshhold
#    $#$self = STAT - 1 if $hit_rate &gt; 0.20; 
#  }

  if (exists $self-&gt;[HASH]{$key}) {
    $self-&gt;[HEAP]-&gt;lookup($self-&gt;[HASH]{$key});
  } else {
    return;
  }
}

# For internal use only
sub _produce {
  my ($self, $key) = @_;
  my $loc = $self-&gt;[HASH]{$key};
  return unless defined $loc;
  $self-&gt;[HEAP][$loc][2];
}

# For internal use only
sub _promote {
  my ($self, $key) = @_;
  $self-&gt;[HEAP]-&gt;promote($self-&gt;[HASH]{$key});
}

sub empty {
  my ($self) = @_;
  %{$self-&gt;[HASH]} = ();
    $self-&gt;[BYTES] = 0;
    $self-&gt;[HEAP]-&gt;empty;
#  @{$self-&gt;[STAT]} = ();
#    $self-&gt;[MISS] = 0;
#    $self-&gt;[REQ] = 0;
}

sub is_empty {
  my ($self) = @_;
  keys %{$self-&gt;[HASH]} == 0;
}

sub update {
  my ($self, $key, $val) = @_;
  local *_;
  croak "missing argument to -&gt;update" unless defined $key;
  if (length($val) &gt; $self-&gt;[MAX]) {
    my ($oldval) = $self-&gt;remove($key);
    $self-&gt;[BYTES] -= length($oldval) if defined $oldval;
  } elsif (exists $self-&gt;[HASH]{$key}) {
    my $oldval = $self-&gt;[HEAP]-&gt;set_val($self-&gt;[HASH]{$key}, $val);
    $self-&gt;[BYTES] += length($val);
    $self-&gt;[BYTES] -= length($oldval) if defined $oldval;
  } else {
    $self-&gt;[HEAP]-&gt;insert($key, $val);
    $self-&gt;[BYTES] += length($val);
  }
  $self-&gt;flush;
}

sub rekey {
  my ($self, $okeys, $nkeys) = @_;
  local *_;
  my %map;
  @map{@$okeys} = @$nkeys;
  croak "missing argument to -&gt;rekey" unless defined $nkeys;
  croak "length mismatch in -&gt;rekey arguments" unless @$nkeys == @$okeys;
  my %adjusted;                 # map new keys to heap indices
  # You should be able to cut this to one loop TODO XXX
  for (0 .. $#$okeys) {
    $adjusted{$nkeys-&gt;[$_]} = delete $self-&gt;[HASH]{$okeys-&gt;[$_]};
  }
  while (my ($nk, $ix) = each %adjusted) {
    # @{$self-&gt;[HASH]}{keys %adjusted} = values %adjusted;
    $self-&gt;[HEAP]-&gt;rekey($ix, $nk);
    $self-&gt;[HASH]{$nk} = $ix;
  }
}

sub ckeys {
  my $self = shift;
  my @a = keys %{$self-&gt;[HASH]};
  @a;
}

# Return total amount of cached data
sub bytes {
  my $self = shift;
  $self-&gt;[BYTES];
}

# Expire oldest item from cache until cache size is smaller than $max
sub reduce_size_to {
  my ($self, $max) = @_;
  until ($self-&gt;[BYTES] &lt;= $max) {
    # Note that Tie::File::Cache::expire has been inlined here
    my $old_data = $self-&gt;[HEAP]-&gt;popheap;
    return unless defined $old_data;
    $self-&gt;[BYTES] -= length $old_data;
  }
}

# Why not just $self-&gt;reduce_size_to($self-&gt;[MAX])?
# Try this when things stabilize   TODO XXX
# If the cache is too full, expire the oldest records
sub flush {
  my $self = shift;
  $self-&gt;reduce_size_to($self-&gt;[MAX]) if $self-&gt;[BYTES] &gt; $self-&gt;[MAX];
}

# For internal use only
sub _produce_lru {
  my $self = shift;
  $self-&gt;[HEAP]-&gt;expire_order;
}

BEGIN { *_ci_warn = \&amp;Tie::File::_ci_warn }

sub _check_integrity {          # For CACHE
  my $self = shift;
  my $good = 1;

  # Test HEAP
  $self-&gt;[HEAP]-&gt;_check_integrity or $good = 0;

  # Test HASH
  my $bytes = 0;
  for my $k (keys %{$self-&gt;[HASH]}) {
    if ($k ne '0' &amp;&amp; $k !~ /^[1-9][0-9]*$/) {
      $good = 0;
      _ci_warn "Cache hash key &lt;$k&gt; is non-numeric";
    }

    my $h = $self-&gt;[HASH]{$k};
    if (! defined $h) {
      $good = 0;
      _ci_warn "Heap index number for key $k is undefined";
    } elsif ($h == 0) {
      $good = 0;
      _ci_warn "Heap index number for key $k is zero";
    } else {
      my $j = $self-&gt;[HEAP][$h];
      if (! defined $j) {
        $good = 0;
        _ci_warn "Heap contents key $k (=&gt; $h) are undefined";
      } else {
        $bytes += length($j-&gt;[2]);
        if ($k ne $j-&gt;[1]) {
          $good = 0;
          _ci_warn "Heap contents key $k (=&gt; $h) is $j-&gt;[1], should be $k";
        }
      }
    }
  }

  # Test BYTES
  if ($bytes != $self-&gt;[BYTES]) {
    $good = 0;
    _ci_warn "Total data in cache is $bytes, expected $self-&gt;[BYTES]";
  }

  # Test MAX
  if ($bytes &gt; $self-&gt;[MAX]) {
    $good = 0;
    _ci_warn "Total data in cache is $bytes, exceeds maximum $self-&gt;[MAX]";
  }

  return $good;
}

sub delink {
  my $self = shift;
  $self-&gt;[HEAP] = undef;        # Bye bye heap
}

################################################################
#
# Tie::File::Heap
#
# Heap data structure for use by cache LRU routines

package Tie::File::Heap;
use Carp ':DEFAULT', 'confess';
$Tie::File::Heap::VERSION = $Tie::File::Cache::VERSION;
sub SEQ () { 0 };
sub KEY () { 1 };
sub DAT () { 2 };

sub new {
  my ($pack, $cache) = @_;
  die "$pack: Parent cache object $cache does not support _heap_move method"
    unless eval { $cache-&gt;can('_heap_move') };
  my $self = [[0,$cache,0]];
  bless $self =&gt; $pack;
}

# Allocate a new sequence number, larger than all previously allocated numbers
sub _nseq {
  my $self = shift;
  $self-&gt;[0][0]++;
}

sub _cache {
  my $self = shift;
  $self-&gt;[0][1];
}

sub _nelts {
  my $self = shift;
  $self-&gt;[0][2];
}

sub _nelts_inc {
  my $self = shift;
  ++$self-&gt;[0][2];
}  

sub _nelts_dec {
  my $self = shift;
  --$self-&gt;[0][2];
}  

sub is_empty {
  my $self = shift;
  $self-&gt;_nelts == 0;
}

sub empty {
  my $self = shift;
  $#$self = 0;
  $self-&gt;[0][2] = 0;
  $self-&gt;[0][0] = 0;            # might as well reset the sequence numbers
}

# notify the parent cache object that we moved something
sub _heap_move {
  my $self = shift;
  $self-&gt;_cache-&gt;_heap_move(@_);
}

# Insert a piece of data into the heap with the indicated sequence number.
# The item with the smallest sequence number is always at the top.
# If no sequence number is specified, allocate a new one and insert the
# item at the bottom.
sub insert {
  my ($self, $key, $data, $seq) = @_;
  $seq = $self-&gt;_nseq unless defined $seq;
  $self-&gt;_insert_new([$seq, $key, $data]);
}

# Insert a new, fresh item at the bottom of the heap
sub _insert_new {
  my ($self, $item) = @_;
  my $i = @$self;
  $i = int($i/2) until defined $self-&gt;[$i/2];
  $self-&gt;[$i] = $item;
  $self-&gt;[0][1]-&gt;_heap_move($self-&gt;[$i][KEY], $i);
  $self-&gt;_nelts_inc;
}

# Insert [$data, $seq] pair at or below item $i in the heap.
# If $i is omitted, default to 1 (the top element.)
sub _insert {
  my ($self, $item, $i) = @_;
#  $self-&gt;_check_loc($i) if defined $i;
  $i = 1 unless defined $i;
  until (! defined $self-&gt;[$i]) {
    if ($self-&gt;[$i][SEQ] &gt; $item-&gt;[SEQ]) { # inserted item is older
      ($self-&gt;[$i], $item) = ($item, $self-&gt;[$i]);
      $self-&gt;[0][1]-&gt;_heap_move($self-&gt;[$i][KEY], $i);
    }
    # If either is undefined, go that way.  Otherwise, choose at random
    my $dir;
    $dir = 0 if !defined $self-&gt;[2*$i];
    $dir = 1 if !defined $self-&gt;[2*$i+1];
    $dir = int(rand(2)) unless defined $dir;
    $i = 2*$i + $dir;
  }
  $self-&gt;[$i] = $item;
  $self-&gt;[0][1]-&gt;_heap_move($self-&gt;[$i][KEY], $i);
  $self-&gt;_nelts_inc;
}

# Remove the item at node $i from the heap, moving child items upwards.
# The item with the smallest sequence number is always at the top.
# Moving items upwards maintains this condition.
# Return the removed item.  Return undef if there was no item at node $i.
sub remove {
  my ($self, $i) = @_;
  $i = 1 unless defined $i;
  my $top = $self-&gt;[$i];
  return unless defined $top;
  while (1) {
    my $ii;
    my ($L, $R) = (2*$i, 2*$i+1);

    # If either is undefined, go the other way.
    # Otherwise, go towards the smallest.
    last unless defined $self-&gt;[$L] || defined $self-&gt;[$R];
    $ii = $R if not defined $self-&gt;[$L];
    $ii = $L if not defined $self-&gt;[$R];
    unless (defined $ii) {
      $ii = $self-&gt;[$L][SEQ] &lt; $self-&gt;[$R][SEQ] ? $L : $R;
    }

    $self-&gt;[$i] = $self-&gt;[$ii]; # Promote child to fill vacated spot
    $self-&gt;[0][1]-&gt;_heap_move($self-&gt;[$i][KEY], $i);
    $i = $ii; # Fill new vacated spot
  }
  $self-&gt;[0][1]-&gt;_heap_move($top-&gt;[KEY], undef);
  undef $self-&gt;[$i];
  $self-&gt;_nelts_dec;
  return $top-&gt;[DAT];
}

sub popheap {
  my $self = shift;
  $self-&gt;remove(1);
}

# set the sequence number of the indicated item to a higher number
# than any other item in the heap, and bubble the item down to the
# bottom.
sub promote {
  my ($self, $n) = @_;
#  $self-&gt;_check_loc($n);
  $self-&gt;[$n][SEQ] = $self-&gt;_nseq;
  my $i = $n;
  while (1) {
    my ($L, $R) = (2*$i, 2*$i+1);
    my $dir;
    last unless defined $self-&gt;[$L] || defined $self-&gt;[$R];
    $dir = $R unless defined $self-&gt;[$L];
    $dir = $L unless defined $self-&gt;[$R];
    unless (defined $dir) {
      $dir = $self-&gt;[$L][SEQ] &lt; $self-&gt;[$R][SEQ] ? $L : $R;
    }
    @{$self}[$i, $dir] = @{$self}[$dir, $i];
    for ($i, $dir) {
      $self-&gt;[0][1]-&gt;_heap_move($self-&gt;[$_][KEY], $_) if defined $self-&gt;[$_];
    }
    $i = $dir;
  }
}

# Return item $n from the heap, promoting its LRU status
sub lookup {
  my ($self, $n) = @_;
#  $self-&gt;_check_loc($n);
  my $val = $self-&gt;[$n];
  $self-&gt;promote($n);
  $val-&gt;[DAT];
}


# Assign a new value for node $n, promoting it to the bottom of the heap
sub set_val {
  my ($self, $n, $val) = @_;
#  $self-&gt;_check_loc($n);
  my $oval = $self-&gt;[$n][DAT];
  $self-&gt;[$n][DAT] = $val;
  $self-&gt;promote($n);
  return $oval;
}

# The hash key has changed for an item;
# alter the heap's record of the hash key
sub rekey {
  my ($self, $n, $new_key) = @_;
#  $self-&gt;_check_loc($n);
  $self-&gt;[$n][KEY] = $new_key;
}

sub _check_loc {
  my ($self, $n) = @_;
  unless (1 || defined $self-&gt;[$n]) {
    confess "_check_loc($n) failed";
  }
}

BEGIN { *_ci_warn = \&amp;Tie::File::_ci_warn }

sub _check_integrity {
  my $self = shift;
  my $good = 1;
  my %seq;

  unless (eval {$self-&gt;[0][1]-&gt;isa("Tie::File::Cache")}) {
    _ci_warn "Element 0 of heap corrupt";
    $good = 0;
  }
  $good = 0 unless $self-&gt;_satisfies_heap_condition(1);
  for my $i (2 .. $#{$self}) {
    my $p = int($i/2);          # index of parent node
    if (defined $self-&gt;[$i] &amp;&amp; ! defined $self-&gt;[$p]) {
      _ci_warn "Element $i of heap defined, but parent $p isn't";
      $good = 0;
    }

    if (defined $self-&gt;[$i]) {
      if ($seq{$self-&gt;[$i][SEQ]}) {
        my $seq = $self-&gt;[$i][SEQ];
        _ci_warn "Nodes $i and $seq{$seq} both have SEQ=$seq";
        $good = 0;
      } else {
        $seq{$self-&gt;[$i][SEQ]} = $i;
      }
    }
  }

  return $good;
}

sub _satisfies_heap_condition {
  my $self = shift;
  my $n = shift || 1;
  my $good = 1;
  for (0, 1) {
    my $c = $n*2 + $_;
    next unless defined $self-&gt;[$c];
    if ($self-&gt;[$n][SEQ] &gt;= $self-&gt;[$c]) {
      _ci_warn "Node $n of heap does not predate node $c";
      $good = 0 ;
    }
    $good = 0 unless $self-&gt;_satisfies_heap_condition($c);
  }
  return $good;
}

# Return a list of all the values, sorted by expiration order
sub expire_order {
  my $self = shift;
  my @nodes = sort {$a-&gt;[SEQ] &lt;=&gt; $b-&gt;[SEQ]} $self-&gt;_nodes;
  map { $_-&gt;[KEY] } @nodes;
}

sub _nodes {
  my $self = shift;
  my $i = shift || 1;
  return unless defined $self-&gt;[$i];
  ($self-&gt;[$i], $self-&gt;_nodes($i*2), $self-&gt;_nodes($i*2+1));
}

"Cogito, ergo sum.";  # don't forget to return a true value from the file

__END__

=head1 NAME

Tie::File - Access the lines of a disk file via a Perl array

=head1 SYNOPSIS

	# This file documents Tie::File version 0.98
	use Tie::File;

	tie @array, 'Tie::File', filename or die ...;

	$array[13] = 'blah';     # line 13 of the file is now 'blah'
	print $array[42];        # display line 42 of the file

	$n_recs = @array;        # how many records are in the file?
	$#array -= 2;            # chop two records off the end


	for (@array) {
	  s/PERL/Perl/g;         # Replace PERL with Perl everywhere in the file
	}

	# These are just like regular push, pop, unshift, shift, and splice
	# Except that they modify the file in the way you would expect

	push @array, new recs...;
	my $r1 = pop @array;
	unshift @array, new recs...;
	my $r2 = shift @array;
	@old_recs = splice @array, 3, 7, new recs...;

	untie @array;            # all finished


=head1 DESCRIPTION

C&lt;Tie::File&gt; represents a regular text file as a Perl array.  Each
element in the array corresponds to a record in the file.  The first
line of the file is element 0 of the array; the second line is element
1, and so on.

The file is I&lt;not&gt; loaded into memory, so this will work even for
gigantic files.

Changes to the array are reflected in the file immediately.

Lazy people and beginners may now stop reading the manual.

=head2 C&lt;recsep&gt;

What is a 'record'?  By default, the meaning is the same as for the
C&lt;E&lt;lt&gt;...E&lt;gt&gt;&gt; operator: It's a string terminated by C&lt;$/&gt;, which is
probably C&lt;"\n"&gt;.  (Minor exception: on DOS and Win32 systems, a
'record' is a string terminated by C&lt;"\r\n"&gt;.)  You may change the
definition of "record" by supplying the C&lt;recsep&gt; option in the C&lt;tie&gt;
call:

	tie @array, 'Tie::File', $file, recsep =&gt; 'es';

This says that records are delimited by the string C&lt;es&gt;.  If the file
contained the following data:

	Curse these pesky flies!\n

then the C&lt;@array&gt; would appear to have four elements:

	"Curse th"
	"e p"
	"ky fli"
	"!\n"

An undefined value is not permitted as a record separator.  Perl's
special "paragraph mode" semantics (E&lt;agrave&gt; la C&lt;$/ = ""&gt;) are not
emulated.

Records read from the tied array do not have the record separator
string on the end; this is to allow

	$array[17] .= "extra";

to work as expected.

(See L&lt;"autochomp"&gt;, below.)  Records stored into the array will have
the record separator string appended before they are written to the
file, if they don't have one already.  For example, if the record
separator string is C&lt;"\n"&gt;, then the following two lines do exactly
the same thing:

	$array[17] = "Cherry pie";
	$array[17] = "Cherry pie\n";

The result is that the contents of line 17 of the file will be
replaced with "Cherry pie"; a newline character will separate line 17
from line 18.  This means that this code will do nothing:

	chomp $array[17];

Because the C&lt;chomp&gt;ed value will have the separator reattached when
it is written back to the file.  There is no way to create a file
whose trailing record separator string is missing.

Inserting records that I&lt;contain&gt; the record separator string is not
supported by this module.  It will probably produce a reasonable
result, but what this result will be may change in a future version.
Use 'splice' to insert records or to replace one record with several.

=head2 C&lt;autochomp&gt;

Normally, array elements have the record separator removed, so that if
the file contains the text

	Gold
	Frankincense
	Myrrh

the tied array will appear to contain C&lt;("Gold", "Frankincense",
"Myrrh")&gt;.  If you set C&lt;autochomp&gt; to a false value, the record
separator will not be removed.  If the file above was tied with

	tie @gifts, "Tie::File", $gifts, autochomp =&gt; 0;

then the array C&lt;@gifts&gt; would appear to contain C&lt;("Gold\n",
"Frankincense\n", "Myrrh\n")&gt;, or (on Win32 systems) C&lt;("Gold\r\n",
"Frankincense\r\n", "Myrrh\r\n")&gt;.

=head2 C&lt;mode&gt;

Normally, the specified file will be opened for read and write access,
and will be created if it does not exist.  (That is, the flags
C&lt;O_RDWR | O_CREAT&gt; are supplied in the C&lt;open&gt; call.)  If you want to
change this, you may supply alternative flags in the C&lt;mode&gt; option.
See L&lt;Fcntl&gt; for a listing of available flags.
For example:

	# open the file if it exists, but fail if it does not exist
	use Fcntl 'O_RDWR';
	tie @array, 'Tie::File', $file, mode =&gt; O_RDWR;

	# create the file if it does not exist
	use Fcntl 'O_RDWR', 'O_CREAT';
	tie @array, 'Tie::File', $file, mode =&gt; O_RDWR | O_CREAT;

	# open an existing file in read-only mode
	use Fcntl 'O_RDONLY';
	tie @array, 'Tie::File', $file, mode =&gt; O_RDONLY;

Opening the data file in write-only or append mode is not supported.

=head2 C&lt;memory&gt;

This is an upper limit on the amount of memory that C&lt;Tie::File&gt; will
consume at any time while managing the file.  This is used for two
things: managing the I&lt;read cache&gt; and managing the I&lt;deferred write
buffer&gt;.

Records read in from the file are cached, to avoid having to re-read
them repeatedly.  If you read the same record twice, the first time it
will be stored in memory, and the second time it will be fetched from
the I&lt;read cache&gt;.  The amount of data in the read cache will not
exceed the value you specified for C&lt;memory&gt;.  If C&lt;Tie::File&gt; wants
to cache a new record, but the read cache is full, it will make room
by expiring the least-recently visited records from the read cache.

The default memory limit is 2Mib.  You can adjust the maximum read
cache size by supplying the C&lt;memory&gt; option.  The argument is the
desired cache size, in bytes.

	# I have a lot of memory, so use a large cache to speed up access
	tie @array, 'Tie::File', $file, memory =&gt; 20_000_000;

Setting the memory limit to 0 will inhibit caching; records will be
fetched from disk every time you examine them.

The C&lt;memory&gt; value is not an absolute or exact limit on the memory
used.  C&lt;Tie::File&gt; objects contains some structures besides the read
cache and the deferred write buffer, whose sizes are not charged
against C&lt;memory&gt;. 

The cache itself consumes about 310 bytes per cached record, so if
your file has many short records, you may want to decrease the cache
memory limit, or else the cache overhead may exceed the size of the
cached data.


=head2 C&lt;dw_size&gt;

(This is an advanced feature.  Skip this section on first reading.)

If you use deferred writing (See L&lt;"Deferred Writing"&gt;, below) then
data you write into the array will not be written directly to the
file; instead, it will be saved in the I&lt;deferred write buffer&gt; to be
written out later.  Data in the deferred write buffer is also charged
against the memory limit you set with the C&lt;memory&gt; option.

You may set the C&lt;dw_size&gt; option to limit the amount of data that can
be saved in the deferred write buffer.  This limit may not exceed the
total memory limit.  For example, if you set C&lt;dw_size&gt; to 1000 and
C&lt;memory&gt; to 2500, that means that no more than 1000 bytes of deferred
writes will be saved up.  The space available for the read cache will
vary, but it will always be at least 1500 bytes (if the deferred write
buffer is full) and it could grow as large as 2500 bytes (if the
deferred write buffer is empty.)

If you don't specify a C&lt;dw_size&gt;, it defaults to the entire memory
limit.

=head2 Option Format

C&lt;-mode&gt; is a synonym for C&lt;mode&gt;.  C&lt;-recsep&gt; is a synonym for
C&lt;recsep&gt;.  C&lt;-memory&gt; is a synonym for C&lt;memory&gt;.  You get the
idea.

=head1 Public Methods

The C&lt;tie&gt; call returns an object, say C&lt;$o&gt;.  You may call

	$rec = $o-&gt;FETCH($n);
	$o-&gt;STORE($n, $rec);

to fetch or store the record at line C&lt;$n&gt;, respectively; similarly
the other tied array methods.  (See L&lt;perltie&gt; for details.)  You may
also call the following methods on this object:

=head2 C&lt;flock&gt;

	$o-&gt;flock(MODE)

will lock the tied file.  C&lt;MODE&gt; has the same meaning as the second
argument to the Perl built-in C&lt;flock&gt; function; for example
C&lt;LOCK_SH&gt; or C&lt;LOCK_EX | LOCK_NB&gt;.  (These constants are provided by
the C&lt;use Fcntl ':flock'&gt; declaration.)

C&lt;MODE&gt; is optional; the default is C&lt;LOCK_EX&gt;.

C&lt;Tie::File&gt; maintains an internal table of the byte offset of each
record it has seen in the file.  

When you use C&lt;flock&gt; to lock the file, C&lt;Tie::File&gt; assumes that the
read cache is no longer trustworthy, because another process might
have modified the file since the last time it was read.  Therefore, a
successful call to C&lt;flock&gt; discards the contents of the read cache
and the internal record offset table.

C&lt;Tie::File&gt; promises that the following sequence of operations will
be safe:

	my $o = tie @array, "Tie::File", $filename;
	$o-&gt;flock;

In particular, C&lt;Tie::File&gt; will I&lt;not&gt; read or write the file during
the C&lt;tie&gt; call.  (Exception: Using C&lt;mode =E&lt;gt&gt; O_TRUNC&gt; will, of
course, erase the file during the C&lt;tie&gt; call.  If you want to do this
safely, then open the file without C&lt;O_TRUNC&gt;, lock the file, and use
C&lt;@array = ()&gt;.)

The best way to unlock a file is to discard the object and untie the
array.  It is probably unsafe to unlock the file without also untying
it, because if you do, changes may remain unwritten inside the object.
That is why there is no shortcut for unlocking.  If you really want to
unlock the file prematurely, you know what to do; if you don't know
what to do, then don't do it.

All the usual warnings about file locking apply here.  In particular,
note that file locking in Perl is B&lt;advisory&gt;, which means that
holding a lock will not prevent anyone else from reading, writing, or
erasing the file; it only prevents them from getting another lock at
the same time.  Locks are analogous to green traffic lights: If you
have a green light, that does not prevent the idiot coming the other
way from plowing into you sideways; it merely guarantees to you that
the idiot does not also have a green light at the same time.

=head2 C&lt;autochomp&gt;

	my $old_value = $o-&gt;autochomp(0);    # disable autochomp option
	my $old_value = $o-&gt;autochomp(1);    #  enable autochomp option

	my $ac = $o-&gt;autochomp();   # recover current value

See L&lt;"autochomp"&gt;, above.

=head2 C&lt;defer&gt;, C&lt;flush&gt;, C&lt;discard&gt;, and C&lt;autodefer&gt;

See L&lt;"Deferred Writing"&gt;, below.

=head2 C&lt;offset&gt;

	$off = $o-&gt;offset($n);

This method returns the byte offset of the start of the C&lt;$n&gt;th record
in the file.  If there is no such record, it returns an undefined
value.

=head1 Tying to an already-opened filehandle

If C&lt;$fh&gt; is a filehandle, such as is returned by C&lt;IO::File&gt; or one
of the other C&lt;IO&gt; modules, you may use:

	tie @array, 'Tie::File', $fh, ...;

Similarly if you opened that handle C&lt;FH&gt; with regular C&lt;open&gt; or
C&lt;sysopen&gt;, you may use:

	tie @array, 'Tie::File', \*FH, ...;

Handles that were opened write-only won't work.  Handles that were
opened read-only will work as long as you don't try to modify the
array.  Handles must be attached to seekable sources of data---that
means no pipes or sockets.  If C&lt;Tie::File&gt; can detect that you
supplied a non-seekable handle, the C&lt;tie&gt; call will throw an
exception.  (On Unix systems, it can detect this.)

Note that Tie::File will only close any filehandles that it opened
internally.  If you passed it a filehandle as above, you "own" the
filehandle, and are responsible for closing it after you have untied
the @array.

=head1 Deferred Writing

(This is an advanced feature.  Skip this section on first reading.)

Normally, modifying a C&lt;Tie::File&gt; array writes to the underlying file
immediately.  Every assignment like C&lt;$a[3] = ...&gt; rewrites as much of
the file as is necessary; typically, everything from line 3 through
the end will need to be rewritten.  This is the simplest and most
transparent behavior.  Performance even for large files is reasonably
good.

However, under some circumstances, this behavior may be excessively
slow.  For example, suppose you have a million-record file, and you
want to do:

	for (@FILE) {
	  $_ = "&gt; $_";
	}

The first time through the loop, you will rewrite the entire file,
from line 0 through the end.  The second time through the loop, you
will rewrite the entire file from line 1 through the end.  The third
time through the loop, you will rewrite the entire file from line 2 to
the end.  And so on.

If the performance in such cases is unacceptable, you may defer the
actual writing, and then have it done all at once.  The following loop
will perform much better for large files:

	(tied @a)-&gt;defer;
	for (@a) {
	  $_ = "&gt; $_";
	}
	(tied @a)-&gt;flush;

If C&lt;Tie::File&gt;'s memory limit is large enough, all the writing will
done in memory.  Then, when you call C&lt;-E&lt;gt&gt;flush&gt;, the entire file
will be rewritten in a single pass.

(Actually, the preceding discussion is something of a fib.  You don't
need to enable deferred writing to get good performance for this
common case, because C&lt;Tie::File&gt; will do it for you automatically
unless you specifically tell it not to.  See L&lt;"Autodeferring"&gt;,
below.)

Calling C&lt;-E&lt;gt&gt;flush&gt; returns the array to immediate-write mode.  If
you wish to discard the deferred writes, you may call C&lt;-E&lt;gt&gt;discard&gt;
instead of C&lt;-E&lt;gt&gt;flush&gt;.  Note that in some cases, some of the data
will have been written already, and it will be too late for
C&lt;-E&lt;gt&gt;discard&gt; to discard all the changes.  Support for
C&lt;-E&lt;gt&gt;discard&gt; may be withdrawn in a future version of C&lt;Tie::File&gt;.

Deferred writes are cached in memory up to the limit specified by the
C&lt;dw_size&gt; option (see above).  If the deferred-write buffer is full
and you try to write still more deferred data, the buffer will be
flushed.  All buffered data will be written immediately, the buffer
will be emptied, and the now-empty space will be used for future
deferred writes.

If the deferred-write buffer isn't yet full, but the total size of the
buffer and the read cache would exceed the C&lt;memory&gt; limit, the oldest
records will be expired from the read cache until the total size is
under the limit.

C&lt;push&gt;, C&lt;pop&gt;, C&lt;shift&gt;, C&lt;unshift&gt;, and C&lt;splice&gt; cannot be
deferred.  When you perform one of these operations, any deferred data
is written to the file and the operation is performed immediately.
This may change in a future version.

If you resize the array with deferred writing enabled, the file will
be resized immediately, but deferred records will not be written.
This has a surprising consequence: C&lt;@a = (...)&gt; erases the file
immediately, but the writing of the actual data is deferred.  This
might be a bug.  If it is a bug, it will be fixed in a future version.

=head2 Autodeferring

C&lt;Tie::File&gt; tries to guess when deferred writing might be helpful,
and to turn it on and off automatically. 

	for (@a) {
	  $_ = "&gt; $_";
	}

In this example, only the first two assignments will be done
immediately; after this, all the changes to the file will be deferred
up to the user-specified memory limit.

You should usually be able to ignore this and just use the module
without thinking about deferring.  However, special applications may
require fine control over which writes are deferred, or may require
that all writes be immediate.  To disable the autodeferment feature,
use

	(tied @o)-&gt;autodefer(0);

or

       	tie @array, 'Tie::File', $file, autodefer =&gt; 0;


Similarly, C&lt;-E&lt;gt&gt;autodefer(1)&gt; re-enables autodeferment, and 
C&lt;-E&lt;gt&gt;autodefer()&gt; recovers the current value of the autodefer setting.


=head1 CONCURRENT ACCESS TO FILES

Caching and deferred writing are inappropriate if you want the same
file to be accessed simultaneously from more than one process.  Other
optimizations performed internally by this module are also
incompatible with concurrent access.  A future version of this module will
support a C&lt;concurrent =E&lt;gt&gt; 1&gt; option that enables safe concurrent access.

Previous versions of this documentation suggested using C&lt;memory
=E&lt;gt&gt; 0&gt; for safe concurrent access.  This was mistaken.  Tie::File
will not support safe concurrent access before version 0.96.

=head1 CAVEATS

(That's Latin for 'warnings'.)

=over 4

=item *

Reasonable effort was made to make this module efficient.  Nevertheless,
changing the size of a record in the middle of a large file will
always be fairly slow, because everything after the new record must be
moved.

=item *

The behavior of tied arrays is not precisely the same as for regular
arrays.  For example:

	# This DOES print "How unusual!"
	undef $a[10];  print "How unusual!\n" if defined $a[10];

C&lt;undef&gt;-ing a C&lt;Tie::File&gt; array element just blanks out the
corresponding record in the file.  When you read it back again, you'll
get the empty string, so the supposedly-C&lt;undef&gt;'ed value will be
defined.  Similarly, if you have C&lt;autochomp&gt; disabled, then

	# This DOES print "How unusual!" if 'autochomp' is disabled
	undef $a[10];
        print "How unusual!\n" if $a[10];

Because when C&lt;autochomp&gt; is disabled, C&lt;$a[10]&gt; will read back as
C&lt;"\n"&gt; (or whatever the record separator string is.)  

There are other minor differences, particularly regarding C&lt;exists&gt;
and C&lt;delete&gt;, but in general, the correspondence is extremely close.

=item *

I have supposed that since this module is concerned with file I/O,
almost all normal use of it will be heavily I/O bound.  This means
that the time to maintain complicated data structures inside the
module will be dominated by the time to actually perform the I/O.
When there was an opportunity to spend CPU time to avoid doing I/O, I
usually tried to take it.

=item *

You might be tempted to think that deferred writing is like
transactions, with C&lt;flush&gt; as C&lt;commit&gt; and C&lt;discard&gt; as
C&lt;rollback&gt;, but it isn't, so don't.

=item *

There is a large memory overhead for each record offset and for each
cache entry: about 310 bytes per cached data record, and about 21 bytes
per offset table entry.

The per-record overhead will limit the maximum number of records you
can access per file. Note that I&lt;accessing&gt; the length of the array
via C&lt;$x = scalar @tied_file&gt; accesses B&lt;all&gt; records and stores their
offsets.  The same for C&lt;foreach (@tied_file)&gt;, even if you exit the
loop early.

=back

=head1 SUBCLASSING

This version promises absolutely nothing about the internals, which
may change without notice.  A future version of the module will have a
well-defined and stable subclassing API.

=head1 WHAT ABOUT C&lt;DB_File&gt;?

People sometimes point out that L&lt;DB_File&gt; will do something similar,
and ask why C&lt;Tie::File&gt; module is necessary.

There are a number of reasons that you might prefer C&lt;Tie::File&gt;.
A list is available at C&lt;http://perl.plover.com/TieFile/why-not-DB_File&gt;.

=head1 AUTHOR

Mark Jason Dominus

To contact the author, send email to: C&lt;mjd-perl-tiefile+@plover.com&gt;

To receive an announcement whenever a new version of this module is
released, send a blank email message to
C&lt;mjd-perl-tiefile-subscribe@plover.com&gt;.

The most recent version of this module, including documentation and
any news of importance, will be available at

	http://perl.plover.com/TieFile/


=head1 LICENSE

C&lt;Tie::File&gt; version 0.96 is copyright (C) 2003 Mark Jason Dominus.

This library is free software; you may redistribute it and/or modify
it under the same terms as Perl itself.

These terms are your choice of any of (1) the Perl Artistic Licence,
or (2) version 2 of the GNU General Public License as published by the
Free Software Foundation, or (3) any later version of the GNU General
Public License.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this library program; it should be in the file C&lt;COPYING&gt;.
If not, write to the Free Software Foundation, Inc., 51 Franklin Street,
Fifth Floor, Boston, MA  02110-1301, USA

For licensing inquiries, contact the author at:

	Mark Jason Dominus
	255 S. Warnock St.
	Philadelphia, PA 19107

=head1 WARRANTY

C&lt;Tie::File&gt; version 0.98 comes with ABSOLUTELY NO WARRANTY.
For details, see the license.

=head1 THANKS

Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the
core when I hadn't written it yet, and for generally being helpful,
supportive, and competent.  (Usually the rule is "choose any one.")
Also big thanks to Abhijit Menon-Sen for all of the same things.

Special thanks to Craig Berry and Peter Prymmer (for VMS portability
help), Randy Kobes (for Win32 portability help), Clinton Pierce and
Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond
the call of duty), Michael G Schwern (for testing advice), and the
rest of the CPAN testers (for testing generally).

Special thanks to Tels for suggesting several speed and memory
optimizations.

Additional thanks to:
Edward Avis /
Mattia Barbon /
Tom Christiansen /
Gerrit Haase /
Gurusamy Sarathy /
Jarkko Hietaniemi (again) /
Nikola Knezevic /
John Kominetz /
Nick Ing-Simmons /
Tassilo von Parseval /
H. Dieter Pearcey /
Slaven Rezic /
Eric Roode /
Peter Scott /
Peter Somu /
Autrijus Tang (again) /
Tels (again) /
Juerd Waalboer /
Todd Rinaldo

=head1 TODO

More tests.  (Stuff I didn't think of yet.)

Paragraph mode?

Fixed-length mode.  Leave-blanks mode.

Maybe an autolocking mode?

For many common uses of the module, the read cache is a liability.
For example, a program that inserts a single record, or that scans the
file once, will have a cache hit rate of zero.  This suggests a major
optimization: The cache should be initially disabled.  Here's a hybrid
approach: Initially, the cache is disabled, but the cache code
maintains statistics about how high the hit rate would be *if* it were
enabled.  When it sees the hit rate get high enough, it enables
itself.  The STAT comments in this code are the beginning of an
implementation of this.

Record locking with fcntl()?  Then the module might support an undo
log and get real transactions.  What a tour de force that would be.

Keeping track of the highest cached record. This would allow reads-in-a-row
to skip the cache lookup faster (if reading from 1..N with empty cache at
start, the last cached value will be always N-1).

More tests.

=cut

</pre></body></html>