1 package List::MoreUtils;
 
   8 use vars qw{ $VERSION @ISA @EXPORT_OK %EXPORT_TAGS };
 
  11     @ISA       = qw{ Exporter DynaLoader };
 
  13         any all none notall true false
 
  14         firstidx first_index lastidx last_index
 
  15         insert_after insert_after_string
 
  17         after after_incl before before_incl
 
  18         firstval first_value lastval last_value
 
  19         each_array each_arrayref
 
  21         mesh zip uniq distinct
 
  28     # Load the XS at compile-time so that redefinition warnings will be
 
  29     # thrown correctly if the XS versions of part or indexes loaded
 
  31         # PERL_DL_NONLAZY must be false, or any errors in loading will just
 
  32         # cause the perl code to be tested
 
  33         local $ENV{PERL_DL_NONLAZY} = 0 if $ENV{PERL_DL_NONLAZY};
 
  35         bootstrap List::MoreUtils $VERSION;
 
  38     } unless $ENV{LIST_MOREUTILS_PP};
 
  41 # Always use Perl apply() until memory leaks are resolved.
 
  44     &$action foreach my @values = @_;
 
  45     wantarray ? @values : $values[-1];
 
  48 # Always use Perl part() until memory leaks are resolved.
 
  50     my ($code, @list) = @_;
 
  52     push @{ $parts[ $code->($_) ] }, $_  foreach @list;
 
  56 # Always use Perl indexes() until memory leaks are resolved.
 
  65 # Load the pure-Perl versions of the other functions if needed
 
  66 eval <<'END_PERL' unless defined &any;
 
  68 # Use pure scalar boolean return values for compatibility with XS
 
  69 use constant YES => ! 0;
 
  70 use constant NO  => ! 1;
 
  83         return NO unless $f->();
 
  99         return YES unless $f->();
 
 117         $count++ unless $f->();
 
 124     foreach my $i ( 0 .. $#_ ) {
 
 133     foreach my $i ( reverse 0 .. $#_ ) {
 
 140 sub insert_after (&$\@) {
 
 141     my ($f, $val, $list) = @_;
 
 144     foreach my $i ( 0 .. $#$list ) {
 
 146         $c = $i, last if $f->();
 
 151         @{$list}[ $c + 1 .. $#$list ],
 
 152     ) and return 1 if $c != -1;
 
 156 sub insert_after_string ($$\@) {
 
 157     my ($string, $val, $list) = @_;
 
 159     foreach my $i ( 0 .. $#$list ) {
 
 161         $c = $i, last if $string eq $list->[$i];
 
 166         @{$list}[ $c + 1 .. $#$list ],
 
 167     ) and return 1 if $c != -1;
 
 175     grep $started ||= do {
 
 182 sub after_incl (&@) {
 
 185     grep $started ||= $test->(), @_;
 
 191     grep $more &&= ! $test->(), @_;
 
 194 sub before_incl (&@) {
 
 208     for ( $ix = $#_; $ix >= 0; $ix-- ) {
 
 210         my $testval = $test->();
 
 212         # Simulate $_ as alias
 
 214         return $_ if $testval;
 
 222         return $_ if $test->();
 
 227 sub pairwise (&\@\@) {
 
 230     # Symbols for caller's input arrays
 
 231     use vars qw{ @A @B };
 
 232     local ( *A, *B ) = @_;
 
 235     my ( $caller_a, $caller_b ) = do {
 
 238         \*{$pkg.'::a'}, \*{$pkg.'::b'};
 
 241     # Loop iteration limit
 
 242     my $limit = $#A > $#B? $#A : $#B;
 
 244     # This map expression is also the return value
 
 245     local( *$caller_a, *$caller_b );
 
 247         # Assign to $a, $b as refs to caller's array elements
 
 248         ( *$caller_a, *$caller_b ) = \( $A[$_], $B[$_] );
 
 250         # Perform the transformation
 
 255 sub each_array (\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) {
 
 256     return each_arrayref(@_);
 
 260     my @list  = @_; # The list of references to the arrays
 
 261     my $index = 0;  # Which one the caller will get next
 
 262     my $max   = 0;  # Number of elements in longest array
 
 264     # Get the length of the longest input array
 
 266         unless ( ref $_ eq 'ARRAY' ) {
 
 268             Carp::croak("each_arrayref: argument is not an array reference\n");
 
 270         $max = @$_ if @$_ > $max;
 
 273     # Return the iterator as a closure wrt the above variables.
 
 277             unless ( $method eq 'index' ) {
 
 279                 Carp::croak("each_array: unknown argument '$method' passed to iterator.");
 
 282             # Return current (last fetched) index
 
 283             return undef if $index == 0  ||  $index > $max;
 
 287         # No more elements to return
 
 288         return if $index >= $max;
 
 291         # Return ith elements
 
 292         return map $_->[$i], @list; 
 
 300         return splice @list, 0, $n;
 
 304 sub mesh (\@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) {
 
 306     $max < $#$_ && ( $max = $#$_ ) foreach @_;
 
 315     grep { not $seen{$_}++ } @_;
 
 320     my $min = my $max = $_[0];
 
 322     for ( my $i = 1; $i < @_; $i += 2 ) {
 
 323         if ( $_[$i-1] <= $_[$i] ) {
 
 324             $min = $_[$i-1] if $min > $_[$i-1];
 
 325             $max = $_[$i]   if $max < $_[$i];
 
 327             $min = $_[$i]   if $min > $_[$i];
 
 328             $max = $_[$i-1] if $max < $_[$i-1];
 
 334         if ($_[$i-1] <= $_[$i]) {
 
 335             $min = $_[$i-1] if $min > $_[$i-1];
 
 336             $max = $_[$i]   if $max < $_[$i];
 
 338             $min = $_[$i]   if $min > $_[$i];
 
 339             $max = $_[$i-1] if $max < $_[$i-1];
 
 354 *first_index = \&firstidx;
 
 355 *last_index  = \&lastidx;
 
 356 *first_value = \&firstval;
 
 357 *last_value  = \&lastval;
 
 369 List::MoreUtils - Provide the stuff missing in List::Util
 
 373     use List::MoreUtils qw{
 
 374         any all none notall true false
 
 375         firstidx first_index lastidx last_index
 
 376         insert_after insert_after_string
 
 378         after after_incl before before_incl
 
 379         firstval first_value lastval last_value
 
 380         each_array each_arrayref
 
 382         mesh zip uniq distinct minmax part
 
 387 B<List::MoreUtils> provides some trivial but commonly needed functionality on
 
 388 lists which is not going to go into L<List::Util>.
 
 390 All of the below functions are implementable in only a couple of lines of Perl
 
 391 code. Using the functions from this module however should give slightly better
 
 392 performance as everything is implemented in C. The pure-Perl implementation of
 
 393 these functions only serves as a fallback in case the C portions of this module
 
 394 couldn't be compiled on this machine.
 
 400 Returns a true value if any item in LIST meets the criterion given through
 
 401 BLOCK. Sets C<$_> for each item in LIST in turn:
 
 403     print "At least one value undefined"
 
 404         if any { ! defined($_) } @list;
 
 406 Returns false otherwise, or if LIST is empty.
 
 410 Returns a true value if all items in LIST meet the criterion given through
 
 411 BLOCK. Sets C<$_> for each item in LIST in turn:
 
 413     print "All items defined"
 
 414         if all { defined($_) } @list;
 
 416 Returns false otherwise, or if LIST is empty.
 
 418 =item none BLOCK LIST
 
 420 Logically the negation of C<any>. Returns a true value if no item in LIST meets
 
 421 the criterion given through BLOCK. Sets C<$_> for each item in LIST in turn:
 
 423     print "No value defined"
 
 424         if none { defined($_) } @list;
 
 426 Returns false otherwise, or if LIST is empty.
 
 428 =item notall BLOCK LIST
 
 430 Logically the negation of C<all>. Returns a true value if not all items in LIST
 
 431 meet the criterion given through BLOCK. Sets C<$_> for each item in LIST in
 
 434     print "Not all values defined"
 
 435         if notall { defined($_) } @list;
 
 437 Returns false otherwise, or if LIST is empty.
 
 439 =item true BLOCK LIST
 
 441 Counts the number of elements in LIST for which the criterion in BLOCK is true.
 
 442 Sets C<$_> for  each item in LIST in turn:
 
 444     printf "%i item(s) are defined", true { defined($_) } @list;
 
 446 =item false BLOCK LIST
 
 448 Counts the number of elements in LIST for which the criterion in BLOCK is false.
 
 449 Sets C<$_> for each item in LIST in turn:
 
 451     printf "%i item(s) are not defined", false { defined($_) } @list;
 
 453 =item firstidx BLOCK LIST
 
 455 =item first_index BLOCK LIST
 
 457 Returns the index of the first element in LIST for which the criterion in BLOCK
 
 458 is true. Sets C<$_> for each item in LIST in turn:
 
 460     my @list = (1, 4, 3, 2, 4, 6);
 
 461     printf "item with index %i in list is 4", firstidx { $_ == 4 } @list;
 
 463     item with index 1 in list is 4
 
 465 Returns C<-1> if no such item could be found.
 
 467 C<first_index> is an alias for C<firstidx>.
 
 469 =item lastidx BLOCK LIST
 
 471 =item last_index BLOCK LIST
 
 473 Returns the index of the last element in LIST for which the criterion in BLOCK
 
 474 is true. Sets C<$_> for each item in LIST in turn:
 
 476     my @list = (1, 4, 3, 2, 4, 6);
 
 477     printf "item with index %i in list is 4", lastidx { $_ == 4 } @list;
 
 479     item with index 4 in list is 4
 
 481 Returns C<-1> if no such item could be found.
 
 483 C<last_index> is an alias for C<lastidx>.
 
 485 =item insert_after BLOCK VALUE LIST
 
 487 Inserts VALUE after the first item in LIST for which the criterion in BLOCK is
 
 488 true. Sets C<$_> for each item in LIST in turn.
 
 490     my @list = qw/This is a list/;
 
 491     insert_after { $_ eq "a" } "longer" => @list;
 
 494     This is a longer list
 
 496 =item insert_after_string STRING VALUE LIST
 
 498 Inserts VALUE after the first item in LIST which is equal to STRING. 
 
 500     my @list = qw/This is a list/;
 
 501     insert_after_string "a", "longer" => @list;
 
 504     This is a longer list
 
 506 =item apply BLOCK LIST
 
 508 Applies BLOCK to each item in LIST and returns a list of the values after BLOCK
 
 509 has been applied. In scalar context, the last element is returned.  This
 
 510 function is similar to C<map> but will not modify the elements of the input
 
 514     my @mult = apply { $_ *= 2 } @list;
 
 515     print "\@list = @list\n";
 
 516     print "\@mult = @mult\n";
 
 521 Think of it as syntactic sugar for
 
 523     for (my @mult = @list) { $_ *= 2 }
 
 525 =item before BLOCK LIST
 
 527 Returns a list of values of LIST upto (and not including) the point where BLOCK
 
 528 returns a true value. Sets C<$_> for each element in LIST in turn.
 
 530 =item before_incl BLOCK LIST
 
 532 Same as C<before> but also includes the element for which BLOCK is true.
 
 534 =item after BLOCK LIST
 
 536 Returns a list of the values of LIST after (and not including) the point
 
 537 where BLOCK returns a true value. Sets C<$_> for each element in LIST in turn.
 
 539     @x = after { $_ % 5 == 0 } (1..9);    # returns 6, 7, 8, 9
 
 541 =item after_incl BLOCK LIST
 
 543 Same as C<after> but also inclues the element for which BLOCK is true.
 
 545 =item indexes BLOCK LIST
 
 547 Evaluates BLOCK for each element in LIST (assigned to C<$_>) and returns a list
 
 548 of the indices of those elements for which BLOCK returned a true value. This is
 
 549 just like C<grep> only that it returns indices instead of values:
 
 551     @x = indexes { $_ % 2 == 0 } (1..10);   # returns 1, 3, 5, 7, 9
 
 553 =item firstval BLOCK LIST
 
 555 =item first_value BLOCK LIST
 
 557 Returns the first element in LIST for which BLOCK evaluates to true. Each
 
 558 element of LIST is set to C<$_> in turn. Returns C<undef> if no such element
 
 561 C<first_val> is an alias for C<firstval>.
 
 563 =item lastval BLOCK LIST
 
 565 =item last_value BLOCK LIST
 
 567 Returns the last value in LIST for which BLOCK evaluates to true. Each element
 
 568 of LIST is set to C<$_> in turn. Returns C<undef> if no such element has been
 
 571 C<last_val> is an alias for C<lastval>.
 
 573 =item pairwise BLOCK ARRAY1 ARRAY2
 
 575 Evaluates BLOCK for each pair of elements in ARRAY1 and ARRAY2 and returns a
 
 576 new list consisting of BLOCK's return values. The two elements are set to C<$a>
 
 577 and C<$b>.  Note that those two are aliases to the original value so changing
 
 578 them will modify the input arrays.
 
 582     @x = pairwise { $a + $b } @a, @b;   # returns 12, 14, 16, 18, 20
 
 587     @x = pairwise { ($a, $b) } @a, @b;  # returns a, 1, b, 2, c, 3
 
 589 =item each_array ARRAY1 ARRAY2 ...
 
 591 Creates an array iterator to return the elements of the list of arrays ARRAY1,
 
 592 ARRAY2 throughout ARRAYn in turn.  That is, the first time it is called, it
 
 593 returns the first element of each array.  The next time, it returns the second
 
 594 elements.  And so on, until all elements are exhausted.
 
 596 This is useful for looping over more than one array at once:
 
 598     my $ea = each_array(@a, @b, @c);
 
 599     while ( my ($a, $b, $c) = $ea->() )   { .... }
 
 601 The iterator returns the empty list when it reached the end of all arrays.
 
 603 If the iterator is passed an argument of 'C<index>', then it retuns
 
 604 the index of the last fetched set of values, as a scalar.
 
 606 =item each_arrayref LIST
 
 608 Like each_array, but the arguments are references to arrays, not the
 
 611 =item natatime BLOCK LIST
 
 613 Creates an array iterator, for looping over an array in chunks of
 
 614 C<$n> items at a time.  (n at a time, get it?).  An example is
 
 615 probably a better explanation than I could give in words.
 
 619     my @x = ('a' .. 'g');
 
 620     my $it = natatime 3, @x;
 
 621     while (my @vals = $it->())
 
 632 =item mesh ARRAY1 ARRAY2 [ ARRAY3 ... ]
 
 634 =item zip ARRAY1 ARRAY2 [ ARRAY3 ... ]
 
 636 Returns a list consisting of the first elements of each array, then
 
 637 the second, then the third, etc, until all arrays are exhausted.
 
 643     @z = mesh @x, @y;       # returns a, 1, b, 2, c, 3, d, 4
 
 647     @c = qw/zip zap zot/;
 
 648     @d = mesh @a, @b, @c;   # x, 1, zip, undef, 2, zap, undef, undef, zot
 
 650 C<zip> is an alias for C<mesh>.
 
 656 Returns a new list by stripping duplicate values in LIST. The order of
 
 657 elements in the returned list is the same as in LIST. In scalar context,
 
 658 returns the number of unique elements in LIST.
 
 660     my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 1 2 3 5 4
 
 661     my $x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 5
 
 665 Calculates the minimum and maximum of LIST and returns a two element list with
 
 666 the first element being the minimum and the second the maximum. Returns the
 
 667 empty list if LIST was empty.
 
 669 The C<minmax> algorithm differs from a naive iteration over the list where each
 
 670 element is compared to two values being the so far calculated min and max value
 
 671 in that it only requires 3n/2 - 2 comparisons. Thus it is the most efficient
 
 674 However, the Perl implementation of it has some overhead simply due to the fact
 
 675 that there are more lines of Perl code involved. Therefore, LIST needs to be
 
 676 fairly big in order for C<minmax> to win over a naive implementation. This
 
 677 limitation does not apply to the XS version.
 
 679 =item part BLOCK LIST
 
 681 Partitions LIST based on the return value of BLOCK which denotes into which
 
 682 partition the current value is put.
 
 684 Returns a list of the partitions thusly created. Each partition created is a
 
 685 reference to an array.
 
 688     my @part = part { $i++ % 2 } 1 .. 8;   # returns [1, 3, 5, 7], [2, 4, 6, 8]
 
 690 You can have a sparse list of partitions as well where non-set partitions will
 
 693     my @part = part { 2 } 1 .. 10;          # returns undef, undef, [ 1 .. 10 ]
 
 695 Be careful with negative values, though:
 
 697     my @part = part { -1 } 1 .. 10;
 
 699     Modification of non-creatable array value attempted, subscript -1 ...
 
 701 Negative values are only ok when they refer to a partition previously created:
 
 703     my @idx  = ( 0, 1, -1 );
 
 705     my @part = part { $idx[$++ % 3] } 1 .. 8; # [1, 4, 7], [2, 3, 5, 6, 8]
 
 711 Nothing by default. To import all of this module's symbols, do the conventional
 
 713     use List::MoreUtils ':all';
 
 715 It may make more sense though to only import the stuff your program actually
 
 718     use List::MoreUtils qw{ any firstidx };
 
 722 When C<LIST_MOREUTILS_PP> is set, the module will always use the pure-Perl
 
 723 implementation and not the XS one. This environment variable is really just
 
 724 there for the test-suite to force testing the Perl implementation, and possibly
 
 725 for reporting of bugs. I don't see any reason to use it in a production
 
 730 There is a problem with a bug in 5.6.x perls. It is a syntax error to write
 
 733     my @x = apply { s/foo/bar/ } qw{ foo bar baz };
 
 735 It has to be written as either
 
 737     my @x = apply { s/foo/bar/ } 'foo', 'bar', 'baz';
 
 741     my @x = apply { s/foo/bar/ } my @dummy = qw/foo bar baz/;
 
 743 Perl 5.5.x and Perl 5.8.x don't suffer from this limitation.
 
 745 If you have a functionality that you could imagine being in this module, please
 
 746 drop me a line. This module's policy will be less strict than L<List::Util>'s
 
 747 when it comes to additions as it isn't a core module.
 
 749 When you report bugs, it would be nice if you could additionally give me the
 
 750 output of your program with the environment variable C<LIST_MOREUTILS_PP> set
 
 751 to a true value. That way I know where to look for the problem (in XS,
 
 752 pure-Perl or possibly both).
 
 756 Bugs should always be submitted via the CPAN bug tracker.
 
 758 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=List-MoreUtils>
 
 762 Credits go to a number of people: Steve Purkis for giving me namespace advice
 
 763 and James Keenan and Terrence Branno for their effort of keeping the CPAN
 
 764 tidier by making L<List::Utils> obsolete. 
 
 766 Brian McCauley suggested the inclusion of apply() and provided the pure-Perl
 
 767 implementation for it.
 
 769 Eric J. Roode asked me to add all functions from his module C<List::MoreUtil>
 
 770 into this one. With minor modifications, the pure-Perl implementations of those
 
 773 The bunch of people who almost immediately pointed out the many problems with
 
 774 the glitchy 0.07 release (Slaven Rezic, Ron Savage, CPAN testers).
 
 776 A particularly nasty memory leak was spotted by Thomas A. Lowery.
 
 778 Lars Thegler made me aware of problems with older Perl versions.
 
 780 Anno Siegel de-orphaned each_arrayref().
 
 782 David Filmer made me aware of a problem in each_arrayref that could ultimately
 
 785 Ricardo Signes suggested the inclusion of part() and provided the
 
 788 Robin Huston kindly fixed a bug in perl's MULTICALL API to make the
 
 789 XS-implementation of part() work.
 
 793 A pile of requests from other people is still pending further processing in
 
 794 my mailbox. This includes:
 
 798 =item * List::Util export pass-through
 
 800 Allow B<List::MoreUtils> to pass-through the regular L<List::Util>
 
 801 functions to end users only need to C<use> the one module.
 
 805 Use code-reference to extract a key based on which the uniqueness is
 
 806 determined. Suggested by Aaron Crane.
 
 812 =item * random_item_delete_index
 
 814 =item * list_diff_hash
 
 816 =item * list_diff_inboth
 
 818 =item * list_diff_infirst
 
 820 =item * list_diff_insecond
 
 822 These were all suggested by Dan Muey.
 
 826 Always return a flat list when either a simple scalar value was passed or an
 
 827 array-reference. Suggested by Mark Summersault.
 
 837 Tassilo von Parseval E<lt>tassilo.von.parseval@rwth-aachen.deE<gt>
 
 839 =head1 COPYRIGHT AND LICENSE
 
 841 Copyright 2004 - 2010 by Tassilo von Parseval
 
 843 This library is free software; you can redistribute it and/or modify
 
 844 it under the same terms as Perl itself, either Perl version 5.8.4 or,
 
 845 at your option, any later version of Perl 5 you may have available.