(Depends on the size of the file, and what you are trying to do...Generally speaking)
- If the file is not big, and you have to process many lines, read the whole thing into an array, two line back is just another element of the array, no big deal.
- If the file is big, read in line by line, but always remember the last 4 lines, instead of only the last line.
- If the file is big, and you only care line 10000 and 10003, it would be a big waste to read line by line. seek back can do the trick, but if the records are not fixed-length, you have to deal with new lines and all the calculation, not very ideal.
| [reply] |
You could also read the the file in backward using File::ReadBackwards, then when you find the line you need, just read two more.
I'm inclined to think that is the best solution to your problem assuming the file is of any size at all. Reading the file into an array is slow and memory inefficient and to read forward line by line, you'll have to remember the prior lines somehow, and that's going to involve a lot of data movement (if you use say 4 variables to store the prior lines--you'll be shuffling their values a lot) or a lot of memory (if you're putting the prior lines into an array), slowing your program down.
Edited to add example:
use File::ReadBackwards;
$bw = File::ReadBackwards->new( 'log_file' ) or
die "can't read 'log_file' $!" ;
until ( $bw->eof ) {
last if ($bw->readline =~ m/$search_string/);
}
$prior_line_1 = $bw->readline;
$prior_line_2 = $bw->readline;
| [reply] [d/l] |
my ($buf, $onelineback, $twolinesback, $thisline);
while($buf = <IN>) {
if ($buf =~ /somestring/) {
if defined($twolinesback) {
print $twolinesback;
} else {
print "Matched, but not enough lines read yet\n";
}
}
$twolinesback = $onelineback;
$onelineback = $thisline;
$thisline = $buf;
}
| [reply] [d/l] |