in reply to RFC: Tying Filehandles
Very interesting idea. I decided to have a hack at it myself (code below). However, I stressed different aspects of the problem, so it's not exactly apples and apples, but a benchmark comparison would still be interesting. I predict that you incur significant overhead by having to deal with the regex record delimiter and the "read-ahead" buffer.
Some features of this code:package Tie::Handle::MultiRec; use Carp; sub TIEHANDLE { my $pkg = shift; my $fn = shift; my $irs = shift || "\n"; my $n = shift || 1; my $fh = *main::STDIN; # default $fn and open $fh, "<", $fn or croak "read $fn - $!\n"; bless { readline => sub { local $/ = $irs; my $s; for ( 1 .. $n ) { eof($fh) and return $s; $s .= <$fh>; } $s }, n => sub { @_ and $n = shift; $n }, print => sub { for (@_) { /^N\w*=(\d+)/mi and $n = $1; /^I\w*="(.*?)"/msi and $irs = $1; } }, }, $pkg; } sub READLINE { $_[0]{'readline'}->() } sub N { $_[0]{'n'}->($_[1]) } sub PRINT { my $self = shift; $self->{'print'}->(@_); }
my $ctl = tie *FH, 'Tie::Handle::MultiRec', $0, "\n", 3; my $n = 1; while (<FH>) { print "Record $n:\n$_\n\n"; $ctl->N(3+$n); # get more lines per read (the conventional way) print FH qq(irs=""); # switch to paragraph mode (using OOB) $n++; }
|
|---|