I'm attempting to get the last 15 minutes of entries from a httpd access log. I immediately think of a binary search. The problem is, I've never written one. I've attempted to use this code example from the book:Mastering Algorithms with Perl. But it doesn't work for my purpose. Can someone offer help? I'm assuming the best way to search would be based on the date string: perl binary_search_file.pl "Aug 3 07:59:59"
#!/usr/bin/perl -w
use strict;
use integer;
my ( $word, $file ) = @ARGV;
open( FILE, $file ) or die "Can't open $file: $!";
my $position = binary_search_file( \*FILE, $word );
if ( defined $position ) { print "$word occurs at position $position
+\n" }
else { print "$word does not occur in $file.\n"
+}
sub binary_search_file {
my ( $file, $word ) = @_;
my ( $high, $low, $mid, $mid2, $line );
$low = 0; # Guaranteed to be the start of a l
+ine.
$high = ( stat($file) )[7]; # Might not be the start of a line.
$word =~ s/\W//g; # Remove punctuation from $word.
$word = lc($word); # Convert $word to lower case.
while ( $high != $low ) {
$mid = ( $high + $low ) / 2;
seek( $file, $mid, 0 ) || die "Couldn't seek : $!\n";
# $mid is probably in the middle of a line, so read the rest
# and set $mid2 to that new position.
$line = <$file>;
$mid2 = tell($file);
if ( $mid2 < $high ) { # We're not near file's end, so rea
+d on.
$mid = $mid2;
$line = <$file>;
}
else { # $mid plunked us in the last line, so linear search
+.
seek( $file, $low, 0 ) || die "Couldn't seek: $!\n";
while ( defined( $line = <$file> ) ) {
last if compare( $line, $word ) >= 0;
$low = tell($file);
}
last;
}
if ( compare( $line, $word ) < 0 ) { $low = $mid }
else { $high = $mid }
}
return if compare( $line, $word );
return $low;
}
sub compare { # $word1 needs to be lowercased; $word2 doesn't.
my ( $word1, $word2 ) = @_;
$word1 =~ s/\W//g;
$word1 = lc($word1);
return $word1 cmp $word2;
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.