in reply to In need of a sequence iterator.
There's gotta be a better way than this:
use strict; use warnings; sub genIterator_helper($\@) { my ($base, $list) = @_; my $i = $#$list; for (;;) { last if (++$$list[$i] < $base); $$list[$i] = 0; return undef unless $i; $i--; } return 1; } sub genIterator { my ($max_digits, $base) = @_; my @list; foreach my $num_digits (1..4) { my @digits = (0) x $num_digits; do { push(@list, join('', @digits)); } while (genIterator_helper($base, @digits)); } @list = sort { $a cmp $b } @list; return sub { shift(@list) }; } my $iter = genIterator(4, 3); print "$_$/" while defined ($_ = $iter->());
|
|---|