ongaku has asked for the wisdom of the Perl Monks concerning the following question:
And the output I get:tie @lines, 'TieFile', 'just_lines'; print $lines[20]; exit; package TieFile; use Symbol; #use strict; my $F_OFFSETS = 0; my $F_FILEHANDLE = 1; sub TIEARRAY { my ($pkg, $filename) = @_; my $fh = gensym(); open ($fh, $filename) || die "Could not open file: $!\n"; print "TIEARRAY:\$fh=$fh\n"; # correctly says it is a glob bless [ [0], $fh # stores it here ], $pkg; } sub FETCH { print "fetch:\$F_FILEHANDLE=$F_FILEHANDLE\n"; # F_FILEHANDLE has d +isappeared! print "defined!\n" if defined ($F_FILEHANDLE); print "not defined!\n" if !defined ($F_FILEHANDLE); my ($obj, $index) = @_; my $rl_offsets = $obj->[$F_OFFSETS]; my $fh = $obj->[$F_FILEHANDLE]; # my $fh = $obj->[1]; print "fetch:\$fh=$fh\n"; print "fetch:\$rl_offsets=$rl_offsets\n"; if ($index > @$rl_offsets) { print "reading_until\n"; $obj->read_until($index); } else { seek ($fh, $rl_offsets->[$index], 0); } return (scalar<$fh>); } sub STORE { die "Sorry, cannot update file using package TieFile\n"; } sub DESTROY { my ($obj) = @_; close ($obj->[$F_FILEHANDLE]); } sub read_until { my ($obj, $index) = @_; my $rl_offsets = $obj->[$F_OFFSETS]; my $last_index = @$rl_offsets - 1; my $last_offset = $rl_offsets->[$last_index]; my $fh = $obj->[$F_FILEHANDLE]; print "read_until:\$fh=$fh\n"; seek ($fh, $last_offset, 0); my $buf; while (defined($buf = <$fh>)) { $last_offset += length($buf); $last_index++; push (@$rl_offsets, $last_offset); last if ($last_index > $index); } } 1;
TIEARRAY:$fh=GLOB(0x10011028) fetch:$F_FILEHANDLE= not defined! fetch:$fh=ARRAY(0x1002e8bc) fetch:$rl_offsets=ARRAY(0x1002e8bc) reading_until read_until:$fh=ARRAY(0x1002e8bc) Not a GLOB reference at TieFile.pm line 56.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: TIEARRAY example out of date?
by lamprecht (Friar) on Feb 26, 2010 at 23:08 UTC |