Hi,
using some functional programming to create an iterator you can end up with something like this:
use Modern::Perl;
#my $alphabet = ['a'..'z', 'A'..'Z'];
#my $word_length = 6;
my $alphabet = ['a'..'b', '_'];
my $word_length = 3;
sub create_dictionary {
my ($alphabet, $word_length) = @_;
my @odometer = (0) x $word_length;
my $len_alpha = @$alphabet;
my $exhausted = 0;
return sub {
my $str = undef;
if (!$exhausted) {
$str = join('', map { $alphabet->[$_] } @odometer);
my $add = 1;
@odometer = map { $_+=$add; $add = $_ >= $len_alpha ? 1:0
+; $_% $len_alpha } @odometer;
$exhausted = $add; # last carry == 1 => exhausted!
}
return $str;
};
}
my $dict = create_dictionary($alphabet, $word_length);
while (my $word = $dict->()) {
say $word;
}
I got the odometer idea (if I remember correctly) from "higher order perl" http://hop.perl.plover.com/.
k
-
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.
|