Hacked this up yesterday, got it working and then someone pointed me to Search::Dict which did almost exactly this same function. And it's standard distribution. Ah well.

Offered for your enjoyment only. I guess it serves as an example of a binary search and a use for "magical" goto. :)

# Implements a binary search on a sorted word list # (in a text file). Very similar to Search::Dict (a standard # module) so use it instead where appropriate. Intended as an # example of binary-searching a file. # # search("word") returns the byte offset if lowercase "word" # is found in *W # or undef if it's not found. # # (Assumes filehandle W is open to the dictionary file.) sub search { my($word, $start, $end)=@_; my($guess, $offset, $preguess); no warnings 'uninitialized'; $end=-s W unless defined $end; $offset=int(($end-$start)/2+$start); seek(W, $offset, 0); # Go there. while($offset and getc(W) ne "\n") { seek(W, --$offset, 0); } $preguess=tell(W); $guess=<W>; chomp($guess); $guess=lc($guess); return $preguess if $guess eq $word; if ($word gt $guess) { return if ($offset==$_[1] and $end==$_[2]); { local $_=tell(W); if (<W> eq lc("$word\n")) { # Try the next word too +. return $_; } } @_=($word, $preguess, $end); } else { return if ($start==$_[1] and $offset==$_[2]); @_=($word, $start, $preguess); } goto &search; }

In reply to Alternative for Search::Dict by clintp

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



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.