Debian Codegraph @

cassandane/Cassandane/Util/Words.pm

raw
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 2011-2017 FastMail Pty Ltd. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # 3. The name "Fastmail Pty Ltd" must not be used to
18 # endorse or promote products derived from this software without
19 # prior written permission. For permission or any legal
20 # details, please contact
21 # FastMail Pty Ltd
22 # PO Box 234
23 # Collins St West 8007
24 # Victoria
25 # Australia
26 #
27 # 4. Redistributions of any form whatsoever must retain the following
28 # acknowledgment:
29 # "This product includes software developed by Fastmail Pty. Ltd."
30 #
31 # FASTMAIL PTY LTD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
32 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
33 # EVENT SHALL OPERA SOFTWARE AUSTRALIA BE LIABLE FOR ANY SPECIAL, INDIRECT
34 # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
35 # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
36 # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
37 # OF THIS SOFTWARE.
38 #
39
40 package Cassandane::Util::Words;
41 use strict;
42 use warnings;
43
44 use Exporter ();
45 our @ISA = qw(Exporter);
46 our @EXPORT = qw(
47 &random_word
48 &random_words
49 );
50
51 my @words;
52 my @remaining;
53
54 use constant WORDFILE => '/usr/share/dict/words';
55 use constant STRIDE => 7;
56 use constant MAX_WORDS => 2048;
57 use constant MIN_LENGTH => 2;
58 use constant MAX_LENGTH => 7;
59
60 # Extract some well-formatted short words from the dictionary file
61 sub _read_words
62 {
63 my $i = 0;
64 open DICT,'<',WORDFILE
65 or die "Cannot open " . WORDFILE . " for reading: $!";
66 while (<DICT>)
67 {
68 chomp;
69 $_ = lc;
70 next unless m/^[a-z]+$/;
71 next if length $_ > MAX_LENGTH || length $_ < MIN_LENGTH;
72 next if $i++ < STRIDE;
73 $i = 0;
74 push(@words, $_);
75 last if scalar @words == MAX_WORDS;
76 }
77 close DICT;
78 }
79
80 sub random_word
81 {
82 _read_words()
83 if (!scalar @words);
84 @remaining = @words unless scalar @remaining;
85 return $remaining[int(rand(scalar @remaining))];
86 }
87
88 sub random_words
89 {
90 my ($count) = @_;
91 my @random_words;
92
93 while ($count-- > 0) {
94 push @random_words, random_word();
95 }
96
97 return wantarray ? @random_words : "@random_words";
98 }
99
100 1;