in reply to read a file in both directions

Why does this have to be done in a single pass? Reading a file backwards is sufficiently awkward that it pays to use a module such as File::ReadBackwards to handle the ugly work for you. I would probably do it something like this:

use strict; use warnings; use File::ReadBackwards; open my $forward, '<', 'filename.txt' or die $!; while( my $line = <$forward> ) { last if $line eq "\n"; } my $blank_position = tell( $forward ); close $forward; my $bw = File::ReadBackwards->new( 'filename.txt' ) or die "can't read 'filename.txt' $!" ; while( defined( my $bw_line = $bw->readline ) ) { last if $bw->tell() <= $blank_position; print $bw_line; }

This is untested, but should give you the general framework.


Dave

Replies are listed 'Best First'.
Re^2: read a file in both directions
by dynamo (Chaplain) on May 31, 2006 at 11:54 UTC
    The thing about File::ReadBackwards is that it kinda assumes you are reading a log file or other text-oriented data, sorted into records by line, and that you want to read them in backwards order but not actually reverse the lines themselves (not an unreasonable assumption, but I didn't assume it myself.)

    My interpretation of the question was that the data itself should be reversed from the blank line on.. so my code below gives that, while Dave's contribution above gives.. the first thing I said.

    -d