Alex Chen wrote:
> 
> hi, all

Hello,

> i want to know how to get the last line of
> a file .i know the func read has a paramenter offset but i don't know how to
> use it.please help!!!


1)  Install http://search.cpan.org/author/URI/File-ReadBackwards-0.98/

use File::ReadBackwards;
my $bw = File::ReadBackwards->new( 'file' ) or die "Cannot read 'file'
$!";
my $last_line = $bw->readline;


2)  Use the Tie::File module

use Tie::File;
tie my @lines, 'Tie::File', 'file' or die "Cannot read 'file' $!";
my $last_line = $lines[-1];


3)  Read through the whole file

open FILE, 'file' or die "Cannot read 'file' $!";
my $last_line;
$last_line = $_ while <FILE>;


4)  Read the file like File::ReadBackwards does

use Fcntl ':seek';

my $size = 1024;
my $buffer = '';
my $last_line;

sysopen FILE, 'file', O_RDONLY or die "Cannot open 'file' $!";
binmode FILE;

my $pos = sysseek FILE, 0, SEEK_END or die "Cannot seek on 'file' $!";
while ( $pos ) {
    $pos = 0 if ($pos -= $size) < 0;
    sysseek FILE, $pos, SEEK_SET or die "Cannot seek on 'file' $!";
    sysread FILE, my $temp, $size or die "Cannot read 'file' $!";
    chomp( $buffer = $temp . $buffer );
    if ( ( $index = rindex $buffer, $/ ) >= 0 ) {
        $last_line = substr $buffer, $index + length $/;
        last;
        }
    }




John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to