Algorithm-Loops

 view release on metacpan or  search on metacpan

lib/Algorithm/Loops.pm  view on Meta::CPAN

=item OnlyWhen => \&Test

Value must either be a Boolean value or a reference to a subroutine that
will return a Boolean value.

Specifying a true value is the same as specifying a routine that always
returns a true value.  Specifying a false value gives you the default
behavior (as if you did not include the OnlyWhen key at all).

If it is a code reference, then it is called each time a new item is
selected by any of the loops.  The list of selected items is passed in.

The Boolean value returned says whether to use the list of selected
values.  That is, a true value causes either \&Code to be called (if
specified) or the list to be returned by the iterator (if \&Code was not
specified).

If this key does not exist (or is specified with a false value), then a
default subroutine is used, like:

    sub { return @_ == @Loops }

That is, only complete lists are used (by default).  So:

lib/Algorithm/Loops.pm  view on Meta::CPAN


The subroutine that gets called for each iteration.

=head4 Iterator

If you don't pass in a final code reference to NestedLoops, then
NestedLoops will return an iterator to you (without having performed
any iterations yet).

The iterator is a code reference.  Each time you call it, it returns the
next list of selected values.  Any arguments you pass in are ignored (at
least in this release).

=head3 Examples

=head4 Finding non-repeating sequences of digits.

One way would be to loop over all digit combinations but only selecting
ones without repeats:

    use Algorithm::Loops qw/ NestedLoops /;
    $|= 1;
    my $len= 3;
    my $verbose= 1;
    my $count= NestedLoops(
        [   ( [0..9] ) x $len  ],
        {   OnlyWhen => sub {
                    $len == @_

lib/Algorithm/Loops.pm  view on Meta::CPAN

    9 8 6
    7 8 9
    7 9 8
    8 7 9
    8 9 7
    9 7 8
    9 8 7
    720 non-repeating 3-digit sequences.

A third way is to construct the list of values to loop over by excluding
values already selected:

    use Algorithm::Loops qw/ NestedLoops /;
    $|= 1;
    my $len= 3;
    my $verbose= 1;
    my $count= NestedLoops(
        [   [0..9],
            ( sub {
                my %used;
                @used{@_}= (1) x @_;



( run in 0.350 second using v1.01-cache-2.11-cpan-94b05bcf43c )