<?xml version="1.0" encoding="windows-1252"?>
<node id="985296" title="Using binary search to get the last 15 minutes of httpd access log" created="2012-08-03 13:42:10" updated="2012-08-03 13:42:10">
<type id="115">
perlquestion</type>
<author id="265997">
mhearse</author>
<data>
<field name="doctext">
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"

&lt;code&gt;
#!/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 line.
    $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 = &lt;$file&gt;;
        $mid2 = tell($file);

        if ( $mid2 &lt; $high ) {     # We're not near file's end, so read on.
            $mid  = $mid2;
            $line = &lt;$file&gt;;
        }
        else {    # $mid plunked us in the last line, so linear search.
            seek( $file, $low, 0 ) || die "Couldn't seek: $!\n";
            while ( defined( $line = &lt;$file&gt; ) ) { 
                last if compare( $line, $word ) &gt;= 0;
                $low = tell($file);
            }
            last;
        }

        if   ( compare( $line, $word ) &lt; 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;
}
&lt;/code&gt;</field>
</data>
</node>
