in reply to Re^2: Searching text files
in thread Searching text files
Update Forgot to mention: even though this function opens the file every time, it can successfully search 3 million records about 2000 times per second on a 3Ghz Pentium 4. I can't see much justification for anything more complicated. Threads? Bit strings? Crazy! :)# Usage: record_search($search_string, $filename, 11); # Returns the record number if the record is found, undef otherwise. # Searched file must be sorted. sub record_search { my ($key, $filename, $recordsize) = @_; my $fh = IO::File->new($filename, 'r') or croak("Could not open `$filename': $!"); my $hi = ($fh->stat)[7] / $recordsize; my $lo = 0; while ($lo < $hi) { my $mid = int(($lo + $hi) / 2); $fh->seek($mid * $recordsize, 0); my $target = $fh->getline(); chomp($target); if ($target < $key) { $lo = $mid + 1; } elsif ($target == $key) { return $mid; } else { $hi = $mid; } } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: Searching text files
by runrig (Abbot) on Sep 15, 2006 at 18:34 UTC |