I thought I'd mention the solution (to the general problem) Dominus uses in his upcoming book 'Perl Advanced Techniques Handbook' - for appropriate values of solution, of course, the general caveats apply. For more explanation subscribe to his mailing list, you should then get access to the complete chapter, out of which the following code is taken:
#!/usr/bin/perl
use strict;
open my $fh, $ARGV[0] or die "Couldn't open '$ARGV[0]': $!";
my $iter = records( blocks($fh), qr/\s*,\s*/ );
while ( defined(my $rec = $iter->()) ) {
print $rec, "----\n";
}
sub blocks {
my $fh = shift;
my $blocksize = shift || 8192;
sub {
return unless read $fh, my($block), $blocksize;
return $block;
}
}
sub records {
my $blocks = shift;
my $terminator = @_ ? shift : quotemeta($/);
my @records;
my ($buf, $finished) = ("");
sub {
while (@records == 0 && ! $finished) {
if (defined(my $block = $blocks->())) {
$buf .= $block;
my @newrecs = split /($terminator)/, $buf;
while (@newrecs > 2) {
push @records, shift(@newrecs).shift(@newrecs);
}
$buf = join "", @newrecs;
} else {
@records = $buf;
$finished = 1;
}
}
return shift(@records);
}
}
The blocks sub creates an iterator out of a filehandle which returns chunks of a certain blocksize from this filehandle. In this context an iterator is a reference to a function, which when called like this $iter->() returns the next item or undef when the sequence is exhausted. Other methods of creating such a block-creating iterator could be used instead of this sub.
The records sub creates an iterator that returns single records delimited by a terminator - much like the standard perl input iterator <$filehandle> in combination with $/. The difference is that a regular expression is used as a terminator, no longer a fixed length string.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.