loody <[EMAIL PROTECTED]> asked:
> I try to read the last line of a file directly instead of using
> while(<>) or something else to read each line until "undef" 
> bumped to me.
> If you know some build-in functions or another modules for me 
> to use, please help me.

Off the top of my head:

#!/usr/bin/perl -w

use strict;
use Fcntl qw(SEEK_END);

my $file = 'somefile.txt';

open( IN, '<', $file ) or die "Can't open '$file': $!";

my $size = -s $file;
my $found;
my $offset = 256;

while( ! defined( $found ) ){
  # prevent seek from overshooting the start of the file.
  $offset = $size if $offset > $size;
  seek( IN, -$offset, SEEK_END ) or warn "seek failed: $!";

  # read line(s) from filehandle. Ideally, offset was chosen
  # such that @lines contains part of the penultimate line
  # and the last line.
  my @lines = <IN>;

  
  if( @lines > 1 ){
    # more than one lines means we can be sure we do have the last one.
    $found = $lines[ -1 ];
  } elsif( $offset >= $size ) {
    # if we have read the whole file and it's just one line, then that is the 
last line.
    $found = $lines[ 0 ];
  } else {
    # try again with a bigger offset
    $offset += 256;
  }
}

print "The last line is: $found\n";
__END__

HTH,
Thomas

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to