in reply to Random word generator

As others have suggested, if you want a dictionary word, you need a dictionary. The solutions I've seen so far, however, have involved loading the whole dictionary into memory to select your word. I think you could do this without loading the whole dictionary, however. See How do I pick a random line from a file? for the basic algorithm, which could be adapted to apply only to words of a certain length.

Update: I just couldn't resist writing it myself.

use strict; use warnings; my $desired_length = 8; my $selected_word; my $candidate_count = 0; open my $dict_fh, '<', '/usr/share/dict/words' or die "Can't read '/usr/share/dict/words': $!\n"; WORD: while ( my $word = <$dict_fh> ) { chomp $word; next WORD if length $word != $desired_length; $selected_word = $word if rand ++$candidate_count < 1; } print "Selected '$selected_word' out of $candidate_count candidates.\n +";

Replies are listed 'Best First'.
Re^2: Random word generator
by perreal (Monk) on Oct 05, 2010 at 17:07 UTC
    my @word_list; sub rand_word { my $file = shift; if ( not defined $word_list[0] ){ open FIN, "<$file" or die("$file"); @word_list = map { chomp; $_ } <FIN>; close FIN; } my $r = int(rand(@word_list)); return $word_list[$r]; }