sivasakthi wrote:
On Wed, 2007-09-05 at 07:06 -0400, Chas Owens wrote:
On 9/4/07, sivasakthi <[EMAIL PROTECTED]> wrote:
snip
Thanks for your suggestions.. but i need to read a file from backwards...
First time reading from backwards & set the last line position to one
variable..next time reading backwards until reach that variable position...
is it possible to achieve that..????
snip
Yes, just save the value of tell before reading anything (this will be
the end of the file) and then stop reading when you reach that
position in the file. I have included a sample script that does that
very thing. It saves the position in a growing data section at the
end (to give it something to read on the next run). I am having a
hard time coming up with a reason why you would want to read a file
that grows in size backwards; if you don't mind my asking, why do you
need to do such an odd thing?
Thanks for your response..
I have need to collect the possibilities of reading the log files and
submitted to team for analyse....
the following code also achieved my requirement,
#!/usr/bin/perl
use strict;
use warnings;
use File::ReadBackwards ;
my $bw = File::ReadBackwards->new( '/log/path' ) or
die "can't read 'log_file' $!" ;
my $first=1;
open(FH,"position.txt");
$pos=<FH>;
close FH;
my $log_line;
while( defined( $log_line = $bw->readline ) ) {
my $cur_pos=$bw->tell;
if($pos != $cur_pos) {
if($first) {
open(FH,">position.txt");
print FH $cur_pos;
close FH;
undef $first;
}
print "$log_line";
} else {
exit;
}
}
I agree with Chas: I can't help thinking this is like the guy who is asking for
help to remove the petrol tank from his car because he needs to take it to be
filled. I think you are using File::ReadBackwards not because you want the
information in reverse order but because you want to avoid reading all the way
through the log file each time you open it. The File::Tail module is intended
for exactly that purpose, but doesn't allow you to hold your place in the file
across runs of the program. It's not a difficult thing to do though - look at
the
program I have written below (it's untested, although it does compile). It
outputs
the same information as the program you've written, but using standard file
reads.
It also reverses the order of the data as yours does, but if, as I suspect, you
don't need to do that then just change the line
print foreach reverse <$log>;
for
print while <$log>;
which will print the log records in file order as well as reducing the amount of
memory used.
HTH,
Rob
use strict;
use warnings;
open my $log, '/log/path' or die "Uable to open log file: $!";
if (open my $fh,'position.txt') {
my $pos = <$fh>;
close $fh;
seek $log, $pos, 0;
}
print foreach reverse <$log>;
open my $fh, '>', 'position.txt' or die "Unable to write new log position: $!";
print $fh tell $log;
close $fh;
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/