The general method is as you state:

my $find_this = qr/$arbitray data/; open OLD, $log or die $!; open NEW, ">$new_log" or die $!; while (<OLD>) { next unless /$find_this/; print NEW $_ while <OLD>; } close OLD; close NEW; rename $new_log, $log or die $!;

With this code we use the quote regex operator to only compile our regex once to speed it up. We next away until we find our condition and then dump the rest of the file using another while so we never re-enter out outer loop.

Assuming you are using this you have some options:

First you could set up a cron to automatically rename your logfile every X hours - presumably you are just grabbing the last X days/hour/minutes of data so this save you the need.

Alternatively you could check the file size every X hours and record the number. You then use seek LOG, $position, 0 to blast straight to your starting point. The first line will be a partial (probably) so you need to consider that.

As yet another option you can use seek LOG, $offset, $whence If whence is 0 then a positive offset of x gets you x bytes into the file immediately. If $whence is 2 the a negative offset -x gets you to -x bytes from the end. Either way you read in a full line and then use the old halving the difference to find you start point. It's like the guess a number between 1 and 128. You start at 64 higher 96 higher 112 lower 104 higher 108 higher 110 higher - tada must be 111. Thus we have found the number in 7 tries - a big gain on trying all 128 options. The bigger the file the better this will work as it is a geometrical method of finding the start rather than a linear one. The efficiency gain will be highest if the bit you want is a small % of the total file as you still have to write out the new file.

Often when people post their real code we can offer suggestion that increase speed significantly. Hint {smile}




In reply to Re: Removing old records from log files by tachyon
in thread Removing old records from log files by claree0

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":