I like your solution,
lima1.
Here's an example of how one might implement it:
#!/usr/bin/perl -w
# Strict
use strict;
use warnings;
# User-defined
my $wordfile = "words.txt";
# Libraries
use FileHandle;
use File::Basename;
use Data::Dumper;
# Main program
my $iam = basename $0;
# Read words, saving file offsets
my $fh = new FileHandle;
open($fh, '<', $wordfile) or die "$iam: can't read $wordfile ($!)\n";
my ($word, %word_offsets_by_letter);
while (1) {
my $offset = tell($fh);
defined($word = <$fh>) or last;
chomp $word;
if ($word =~ /^(.)/) {
my $first_letter = lc $1;
$word_offsets_by_letter{$first_letter} ||= [ ];
push @{$word_offsets_by_letter{$first_letter}}, $offset;
}
}
# Test (this will give 100 random words beginning with 'a')
foreach (1..100) {
my $next = random_word_starting_with("a", $fh);
print "Next word => $next\n";
}
# Subroutines
#
# random_word_starting_with
#
# In: $1 ... the first letter of the word (eg. 'a', 'b', 'c', etc.)
# $2 ... the open filehandle of the word file
#
sub random_word_starting_with {
my ($first_letter, $fh) = @_;
my $p = $word_offsets_by_letter{lc $first_letter};
my $offset = $p->[int rand @$p];
seek($fh, $offset, 0) or die "$iam: failed to seek ($!)\n";
my $word = <$fh>;
chomp $word;
return $word;
}
And if this is something you need to do a lot of, I like Zaxo's suggestion of using a database.
s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.