in reply to Change the behavior of Perl's IRS
the last chunk isn't read at all
eh? That shouldn't be. Perl returns whatever's after the last $/.
hope that there's a nice and clean way [...] without any ugly corrective code.
I don't know if you'll consider the following "nice and clean", but at least there's no "ugly corrective code" (or any corrective code at all) in the following. It employs a single-line lookahead.
(Update: I've replaced the code I had here originally with a version that hides the guts in an iterator. It's longer, but the usage is much simpler.)
Usage:
my $rec_reader = make_rec_reader('myrecordsep'); while (my $rec = $rec_reader->($fh)) { print("Record\n"); print("======\n"); print "$_\n" for @$rec; print("\n"); }
Guts:
sub make_rec_reader { my ($sep) = @_; my $first = 1; my $line; my @rec; return sub { my ($fh) = @_; # Skip what's before first record. if ($first) { $first = 0; for (;;) { $line = <$fh>; last if not defined $line; chomp($line); last if $line eq $sep; } } while (defined($line)) { my @rec; for (;;) { push @rec, $line; $line = <$fh>; last if not defined $line; chomp($line); last if $line eq $sep; } return \@rec; } }; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Change the behavior of Perl's IRS
by LighthouseJ (Sexton) on Jul 14, 2007 at 19:59 UTC | |
by BrowserUk (Patriarch) on Jul 14, 2007 at 20:10 UTC | |
by ikegami (Patriarch) on Jul 15, 2007 at 07:57 UTC | |
by BrowserUk (Patriarch) on Jul 15, 2007 at 08:04 UTC | |
by ikegami (Patriarch) on Jul 16, 2007 at 02:31 UTC |