Next Tricks of the Wizards 68

Tied Arrays

        package MirrorFile;
        sub TIEARRAY {
          my ($package, $filename) = @_;
          open my $fh, "<", $filename or return;
          my $self = { FH => $fh, FILE => $filename, CACHE => [] };
          bless $self => $package;
        }
        sub FETCH {
          my ($self, $lineno) = @_;
          return $self->{CACHE}[$lineno] 
            if defined $self->{CACHE}[$lineno];
          my $fh = $self->{FH};
          while (<$fh>) {
            push @{$self->{CACHE}}, $_;
            return $_ if $#{$self->{CACHE}} == $lineno;
          }
          return;
        }
        sub FETCHSIZE {
          my ($self) = @_;
          my $fh = $self->{FH};
          push @{$self->{CACHE}}, <$fh>;
          scalar @{$self->{CACHE}};
        }


Next Copyright © 2003 M. J. Dominus