Algorithm-Loops

 view release on metacpan or  search on metacpan

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


For example:

    use Algorithm::Loops qw( Filter );

    @copy = Filter { s/\\(.)/$1/g } @list;
    $text = Filter { s/^\s+// } @lines;

The same process can be accomplished using a careful and more complex
invocation of map, grep, or foreach.  However, many incorrect ways to
attempt this seem rather seductively appropriate so this function helps
to discourage such (rather common) mistakes.

=head3 Usage

Filter has a prototype specification of (\&@).

This means that it demands that the first argument that you pass to it be
a CODE reference.  After that you can pass a list of as many or as few
values as you like.

For each value in the passed-in list, a copy of the value is placed into
$_ and then your CODE reference is called.  Your subroutine is expected
to modify $_ and this modified value is then placed into the list of
values to be returned by Filter.

If used in a scalar context, Filter returns a single string that is the
result of:

    $string= join "", @results;

Note that no arguments are passed to your subroutine (so don't bother
with @_) and any value C<return>ed by your subroutine is ignored.

Filter's prototype also means that you can use the "map BLOCK"-like
syntax by leaving off the C<sub> keyword if you also leave off the
comma after the block that defines your anonymous subroutine:

        my @copy= Filter sub {s/\s/_/g}, @list;
  # becomes:            v^^^       v   ^
        my @copy= Filter {s/\s/_/g} @list;

Most of our examples will use this shorter syntax.

Note also that by importing Filter via the C<use> statement:

    use Algorithm::Loops qw( Filter );

it gets declared before the rest of our code is compiled so we don't have
to use parentheses when calling it.  We I<can> if we want to, however:

        my @copy= Filter( sub {s/\s/_/g}, @list );

=head3 Note on "Function BLOCK LIST" bugs

Note that in at least some versions of Perl, support for the "Filter
BLOCK ..." syntax is somewhat fragile.  For example:

    ... Filter( {y/aeiou/UAEIO/} @list );

may give you this error:

    Array found where operator expected

which can be fixed by dropping the parentheses:

    ... Filter {y/aeiou/UAEIO/} @list;

So if you need or want to use parentheses when calling Filter, it is best
to also include the C<sub> keyword and the comma:

    #         v <--------- These ---------> v
    ... Filter( sub {y/aeiou/UAEIO/}, @list );
    # require   ^^^ <--- these ---> ^ (sometimes)

so your code will be portable to more versions of Perl.

=head3 Examples

Good code ignores "invisible" characters.  So
instead of just chomp()ing, consider removing
all trailing whitespace:

    my @lines= Filter { s/\s+$// } <IN>;

or

    my $line= Filter { s/\s+$// } scalar <IN>;

[ Note that Filter can be used in a scalar
context but always puts its arguments in a
list context.  So we need to use C<scalar> or
something similar if we want to read only one
line at a time from C<IN> above. ]

Want to sort strings that contain mixtures of
letters and natural numbers (non-negative
integers) both alphabetically and numerically
at the same time?  This simple way to do a
"natural" sort is also one of the fastest.
Great for sorting version numbers, file names,
etc.:

    my @sorted= Filter {
        s#\d{2}(\d+)#\1#g
    } sort Filter {
        s#(\d+)# sprintf "%02d%s", length($1), $1 #g
    } @data;

[ Note that at least some versions of Perl have a bug that breaks C<sort>
if you write C<sub {> as part of building the list of items to be sorted
but you don't provide a comparison routine.  This bug means we can't
write the previous code as:

    my @sorted= Filter {
        s#\d{2}(\d+)#\1#g
    } sort Filter sub {
        s#(\d+)# sprintf "%02d%s", length($1), $1 #g
    }, @data;

because it will produce the following error:

    Undefined subroutine in sort

in some versions of Perl.  Some versions of Perl may even require you
to write it like this:

    my @sorted= Filter {
        s#\d{2}(\d+)#\1#g
    } sort &Filter( sub {
        s#(\d+)# sprintf "%02d%s", length($1), $1 #g
    }, @data );

Which is how I wrote it in ex/NaturalSort.plx. ]

Need to sort names?  Then you'll probably want to ignore letter case and
certain punctuation marks while still preserving both:

    my @compare= Filter {tr/A-Z'.,"()/a-z/d} @names;
    my @indices= sort {$compare[$a] cmp $compare[$b]} 0..$#names;
    @names= @names[@indices];

You can also roll your own simple HTML templating:

    print Filter {
        s/%(\w*)%/expand($1)/g
    }   $cgi->...,
        ...
        $cgi->...;

Note that it also also works correctly if you change how you output your
    HTML and accidentally switch from list to scalar context:

    my $html= '';
    ...
    $html .= Filter {
        s/%(\w*)%/expand($1)/g
    }   $cgi->...,
        ...
        $cgi->...;

=head3 Motivation

A reasonable use of map is:

    @copy= map {lc} @list;

which sets @copy to be a copy of @list but with all of the elements
converted to lower case.  But it is too easy to think that that could
also be done like this:

    @copy= map {tr/A-Z/a-z/} @list;  # Wrong

The reason why these aren't the same is similar to why we write:

    $str= lc $str;

not

    lc $str;  # Useless use of 'lc' in void context

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

     for my $b (  $a+1..$N  ) {
      for my $c (  $b+1..$N  ) {
          Stuff( $a, $b, $c );
      }
     }
    }

But what if you want the user to tell you how many loops to nest
together?  The above code can be replaced with:

    use Algorithm::Loops qw( NestedLoops );

    my $depth= 3;
    NestedLoops(
        [   [ 0..$N ],
            ( sub { [$_+1..$N] } ) x ($depth-1),
        ],
        \&Stuff,
    );

Then you only have to change $depth to 4 to get the same results as:

    for my $a (  0..$N  ) {
     for my $b (  $a+1..$N  ) {
      for my $c (  $b+1..$N  ) {
       for my $d (  $c+1..$N  ) {
          Stuff( $a, $b, $c, $d );
       }
      }
     }
    }

=head3 Usage

The first argument to NestedLoops() is required and must be a reference
to an array.  Each element of the array specifies the values for a single
loop to iterate over.  The first element describes the outermost loop. 
The last element describes the innermost loop.

If the next argument to NestedLoops is a hash reference, then it
specifies more advanced options.  This argument can be omitted if you
don't need it.

If the last argument to NestedLoops is a code reference, then it will be
run inside the simulated loops.  If you don't pass in this code
reference, then NestedLoops returns an iterator (described later) so you
can iterate without the restrictions of using a call-back.

So the possible ways to call NestedLoops are:

    $iter= NestedLoops( \@Loops );
    $iter= NestedLoops( \@Loops, \%Opts );
    ...    NestedLoops( \@Loops, \%Opts, \&Code );
    ...    NestedLoops( \@Loops,         \&Code );

The "..."s above show that, when the final code reference is provided,
NestedLoops can return a few different types of information.

In a void context, NestedLoops simply iterates and calls the provided
code, discarding any values it returns.  (Calling NestedLoops in a void
context without passing a final code reference is a fatal error.)

In a list context, NestedLoops C<push>es the values returned by each call
to \&Code onto an array and then returns (copies of the values from) that
array.

In a scalar contetx, NestedLoops keeps a running total of the number of
values returned by each call to \&Code and then returns this total.  The
value is the same as if you had called NestedLoops in a list context and
counted the number of values returned (except for using less memory).

Note that \&Code is called in a list context no matter what context
NestedLoops was called in (in the current implementation).

In summary:

    NestedLoops( \@loops, \%opts, \&code );
    $count= NestedLoops( \@loops, \%opts, \&code );
    @results= NestedLoops( \@loops, \%opts, \&code );

=head4 \@Loops

Each element of @Loops can be

=over 4

=item an array refernce

which means the loop will iterate over the elements of that array,

=item a code refernce

to a subroutine that will return a reference to the array to loop over.

=back

You don't have to use a reference to a named array.  You can, of course,
construct a reference to an anonymous array using C<[...]>, as shown in
most of the examples.  You can also use any other type of expression that
rerurns an array reference.

=head4 \%Opts

If %Opts is passed in, then it should only zero or more of the following
keys.  How NestedLoops interprets the values associated with each key are
described below.

=over 4

=item OnlyWhen => $Boolean

=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



( run in 0.651 second using v1.01-cache-2.11-cpan-6b5c3043376 )