2009/10/25 Michael Alipio <daem0n...@yahoo.com>: > I'm trying to write a word list generator which can > generate all possible combinations of n characters, within n > set of characters.
Have you looked into the magical autoincrement operator? http://perldoc.perl.org/perlop.html#Auto-increment-and-Auto-decrement 1. print ++($foo = '99'); # prints '100' 2. print ++($foo = 'a0'); # prints 'a1' 3. print ++($foo = 'Az'); # prints 'Ba' 4. print ++($foo = 'zz'); # prints 'aaa' my $x; my $len = 4; for ($x = 'a' x $len; $x ne 'a' x ($len+1); $x++) { print "$x\n"; } Or you could specify it as a range: my $len=4; for ('a'x$len..'z'x$len) { print "$_\n"; } These won't help with arbitrary character sets, unfortunately. Gabor wrote: > nd the loops could be replaced by a recursive function > call. Something > like this: > > do_something_for_char($k) > > sub do_something_for_char { > my ($k) = @_; > return if $k >= $n; > do_something_for_char($n+1); > } I would write it differently: sub print_all_strings_of_length { my ($len, $prefix) = @_; $prefix = defined($prefix) ? $prefix : q{}; # or $prefix //= q{}; under recent perls $len < 0 and die qq{print_all_strings_of_length($len) can't be done}; if ($len == 0) { print "$prefix\n"; return; } for ('a'..'z') { # or for (@set) for an arbitrary set of characters print_all_strings_of_length($len-1, $prefix.$_); } return; } print_all_strings_of_length(3); For me, the idea of recursion is expressing an idea in terms of a slightly simpler idea. Here, I express how to print all strings of length N in terms of an operation which will print all strings of length N-1 prefixed with $prefix. So I use that operation to print all strings starting with 'a' followed by N-1 characters, then all strings starting 'b' followed by N-1 characters, and so on. Phil -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/