| 1 | #!perl | ||
| 2 | |||
| 3 | package WWW::ImageSpool::Dictionary; | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | use IO::File; | ||
| 8 | |||
| 9 | return 1; | ||
| 10 | |||
| 11 | sub new | ||
| 12 | { | ||
| 13 | my $class = shift; | ||
| 14 | my $self = bless { @_ }, $class; | ||
| 15 | $self->{file} ||= "/usr/share/dict/words"; | ||
| 16 | $self->{mtime} = -1; | ||
| 17 | if(!-e($self->{file})) | ||
| 18 | { | ||
| 19 | warn "ImageSpool::Dictionary->new() File \"", $self->{file}, "\" does not exist!\n"; | ||
| 20 | return; | ||
| 21 | } | ||
| 22 | elsif(!-r($self->{file})) | ||
| 23 | { | ||
| 24 | warn "ImageSpool::Dictionary->new(): File \"", $self->{file}, "\" is not readable!\n"; | ||
| 25 | return; | ||
| 26 | } | ||
| 27 | elsif(!$self->refresh_words(1)) | ||
| 28 | { | ||
| 29 | return; | ||
| 30 | } | ||
| 31 | |||
| 32 | return $self; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub refresh_words | ||
| 36 | { | ||
| 37 | my($self, $force) = @_; | ||
| 38 | |||
| 39 | my $mtime = -M($self->{file}); | ||
| 40 | |||
| 41 | if(($force) || ($mtime != $self->{mtime}) || (!$self->{words}) || (!scalar(@{$self->{words}}))) | ||
| 42 | { | ||
| 43 | my $fh; | ||
| 44 | if($fh = IO::File->new($self->{file}, "r")) | ||
| 45 | { | ||
| 46 | my(@words) = (grep(!/^$/, $fh->getlines())); | ||
| 47 | $fh->close(); | ||
| 48 | chomp(@words); | ||
| 49 | if(scalar(@words)) | ||
| 50 | { | ||
| 51 | $self->{mtime} = $mtime; | ||
| 52 | $self->{words} = \@words; | ||
| 53 | return scalar(@words); | ||
| 54 | } | ||
| 55 | else | ||
| 56 | { | ||
| 57 | warn "ImageSpool::Dictionary->refresh_words(): No words in dictionary file \"", $self->{file}, "\"!\n"; | ||
| 58 | return; | ||
| 59 | } | ||
| 60 | } | ||
| 61 | else | ||
| 62 | { | ||
| 63 | warn "ImageSpool::Dictionary->refresh_words(): open(", $self->{file}, ") failed: $!\n"; | ||
| 64 | return; | ||
| 65 | } | ||
| 66 | } | ||
| 67 | else | ||
| 68 | { | ||
| 69 | return -1; | ||
| 70 | } | ||
| 71 | } | ||
| 72 | |||
| 73 | sub word | ||
| 74 | { | ||
| 75 | my($self, $consume) = @_; | ||
| 76 | $self->refresh_words(); | ||
| 77 | my $pos = int(rand(scalar(@{$self->{words}}))); | ||
| 78 | my $word = $self->{last_word} = $self->{words}->[$pos]; | ||
| 79 | |||
| 80 | splice(@{$self->{words}}, $pos, 1) | ||
| 81 | if($consume); | ||
| 82 | |||
| 83 | if($self->{verbose} > 3) | ||
| 84 | { | ||
| 85 | print "Picked ", ($consume ? "and consumed " : ""), "word \"$word\".\n"; | ||
| 86 | } | ||
| 87 | |||
| 88 | return $word; | ||
| 89 | } |