File Coverage

blib/lib/List/MoreUtils.pm
Criterion Covered Total %
statement 28 29 96.5
branch 2 6 33.3
condition 2 6 33.3
subroutine 9 9 100.0
pod n/a
total 41 50 82.0


line stmt bran cond sub pod time code
1             package List::MoreUtils;
2              
3 118     118   165788 use 5.008_001;
  118         1414  
4 118     118   1811 use strict;
  118         316  
  118         3755  
5 118     118   786 use warnings;
  118         291  
  118         18466  
6              
7             my $have_xs;
8             our $VERSION = '0.427_001';
9              
10             BEGIN
11 0         0 {
12 118 50   118   2249 unless (defined($have_xs))
13             {
14 118 50       846 eval { require List::MoreUtils::XS; } unless $ENV{LIST_MOREUTILS_PP};
  118         51299  
15 118 0 33     152978 die $@ if $@ && defined $ENV{LIST_MOREUTILS_PP} && $ENV{LIST_MOREUTILS_PP} == 0;
      33        
16 118         4204 $have_xs = 0+defined( $INC{'List/MoreUtils/XS.pm'});
17             }
18              
19 118     118   80654 use List::MoreUtils::PP qw();
  118         512  
  118         4066  
20             }
21              
22 118     118   44685 use Exporter::Tiny qw();
  118         456625  
  118         14914  
23              
24             my @junctions = qw(any all none notall);
25             my @v0_22 = qw(
26             true false
27             firstidx lastidx
28             insert_after insert_after_string
29             apply indexes
30             after after_incl before before_incl
31             firstval lastval
32             each_array each_arrayref
33             pairwise natatime
34             mesh uniq
35             minmax part
36             _XScompiled
37             );
38             my @v0_24 = qw(bsearch);
39             my @v0_33 = qw(sort_by nsort_by);
40             my @v0_400 = qw(one any_u all_u none_u notall_u one_u
41             firstres onlyidx onlyval onlyres lastres
42             singleton bsearchidx
43             );
44             my @v0_420 = qw(arrayify duplicates minmaxstr samples zip6 reduce_0 reduce_1 reduce_u
45             listcmp frequency occurrences mode
46             binsert bremove equal_range lower_bound upper_bound qsort);
47              
48             my @all_functions = (@junctions, @v0_22, @v0_24, @v0_33, @v0_400, @v0_420);
49              
50 118     118   1461 no strict "refs";
  118         355  
  118         13770  
51             if ($have_xs)
52             {
53             my $x;
54             for (@all_functions)
55             {
56             List::MoreUtils->can($_) or *$_ = $x if ($x = List::MoreUtils::XS->can($_));
57             }
58             }
59             List::MoreUtils->can($_) or *$_ = List::MoreUtils::PP->can($_) for (@all_functions);
60 118     118   1091 use strict;
  118         379  
  118         35612  
61              
62             my %alias_list = (
63             v0_22 => {
64             first_index => "firstidx",
65             last_index => "lastidx",
66             first_value => "firstval",
67             last_value => "lastval",
68             zip => "mesh",
69             },
70             v0_33 => {
71             distinct => "uniq",
72             },
73             v0_400 => {
74             first_result => "firstres",
75             only_index => "onlyidx",
76             only_value => "onlyval",
77             only_result => "onlyres",
78             last_result => "lastres",
79             bsearch_index => "bsearchidx",
80             },
81             v0_420 => {
82             bsearch_insert => "binsert",
83             bsearch_remove => "bremove",
84             zip_unflatten => "zip6",
85             },
86             );
87              
88             our @ISA = qw(Exporter::Tiny);
89             our @EXPORT_OK = (@all_functions, map { keys %$_ } values %alias_list);
90             our %EXPORT_TAGS = (
91             all => \@EXPORT_OK,
92             'like_0.22' => [
93             any_u => {-as => 'any'},
94             all_u => {-as => 'all'},
95             none_u => {-as => 'none'},
96             notall_u => {-as => 'notall'},
97             @v0_22,
98             keys %{$alias_list{v0_22}},
99             ],
100             'like_0.24' => [
101             any_u => {-as => 'any'},
102             all_u => {-as => 'all'},
103             notall_u => {-as => 'notall'},
104             'none',
105             @v0_22,
106             @v0_24,
107             keys %{$alias_list{v0_22}},
108             ],
109             'like_0.33' => [
110             @junctions,
111             @v0_22,
112             # v0_24 functions were omitted
113             @v0_33,
114             keys %{$alias_list{v0_22}},
115             keys %{$alias_list{v0_33}},
116             ],
117             );
118              
119             for my $set (values %alias_list)
120             {
121             for my $alias (keys %$set)
122             {
123 118     118   1063 no strict qw(refs);
  118         351  
  118         34769  
124             *$alias = __PACKAGE__->can($set->{$alias});
125             }
126             }
127              
128             =pod
129              
130             =head1 NAME
131              
132             List::MoreUtils - Provide the stuff missing in List::Util
133              
134             =head1 SYNOPSIS
135              
136             # import specific functions
137              
138             use List::MoreUtils qw(any uniq);
139              
140             if ( any { /foo/ } uniq @has_duplicates ) {
141             # do stuff
142             }
143              
144             # import everything
145              
146             use List::MoreUtils ':all';
147              
148             # import by API
149              
150             # has "original" any/all/none/notall behavior
151             use List::MoreUtils ':like_0.22';
152             # 0.22 + bsearch
153             use List::MoreUtils ':like_0.24';
154             # has "simplified" any/all/none/notall behavior + (n)sort_by
155             use List::MoreUtils ':like_0.33';
156              
157             =head1 DESCRIPTION
158              
159             B provides some trivial but commonly needed functionality on
160             lists which is not going to go into L.
161              
162             All of the below functions are implementable in only a couple of lines of Perl
163             code. Using the functions from this module however should give slightly better
164             performance as everything is implemented in C. The pure-Perl implementation of
165             these functions only serves as a fallback in case the C portions of this module
166             couldn't be compiled on this machine.
167              
168             =head1 EXPORTS
169              
170             =head2 Default behavior
171              
172             Nothing by default. To import all of this module's symbols use the C<:all> tag.
173             Otherwise functions can be imported by name as usual:
174              
175             use List::MoreUtils ':all';
176              
177             use List::MoreUtils qw{ any firstidx };
178              
179             Because historical changes to the API might make upgrading List::MoreUtils
180             difficult for some projects, the legacy API is available via special import
181             tags.
182              
183             =head2 Like version 0.22 (last release with original API)
184              
185             This API was available from 2006 to 2009, returning undef for empty lists on
186             C/C/C/C:
187              
188             use List::MoreUtils ':like_0.22';
189              
190             This import tag will import all functions available as of version 0.22.
191             However, it will import C as C, C as C, C as
192             C, and C as C.
193              
194             =head2 Like version 0.24 (first incompatible change)
195              
196             This API was available from 2010 to 2011. It changed the return value of C
197             and added the C function.
198              
199             use List::MoreUtils ':like_0.24';
200              
201             This import tag will import all functions available as of version 0.24.
202             However it will import C as C, C as C, and
203             C as C. It will import C as described in
204             the documentation below (true for empty list).
205              
206             =head2 Like version 0.33 (second incompatible change)
207              
208             This API was available from 2011 to 2014. It is widely used in several CPAN
209             modules and thus it's closest to the current API. It changed the return values
210             of C, C, and C. It added the C and C functions
211             and the C alias for C. It omitted C.
212              
213             use List::MoreUtils ':like_0.33';
214              
215             This import tag will import all functions available as of version 0.33. Note:
216             it will not import C for consistency with the 0.33 API.
217              
218             =head1 FUNCTIONS
219              
220             =head2 Junctions
221              
222             =head3 I
223              
224             There are two schools of thought for how to evaluate a junction on an
225             empty list:
226              
227             =over
228              
229             =item *
230              
231             Reduction to an identity (boolean)
232              
233             =item *
234              
235             Result is undefined (three-valued)
236              
237             =back
238              
239             In the first case, the result of the junction applied to the empty list is
240             determined by a mathematical reduction to an identity depending on whether
241             the underlying comparison is "or" or "and". Conceptually:
242              
243             "any are true" "all are true"
244             -------------- --------------
245             2 elements: A || B || 0 A && B && 1
246             1 element: A || 0 A && 1
247             0 elements: 0 1
248              
249             In the second case, three-value logic is desired, in which a junction
250             applied to an empty list returns C rather than true or false
251              
252             Junctions with a C<_u> suffix implement three-valued logic. Those
253             without are boolean.
254              
255             =head3 all BLOCK LIST
256              
257             =head3 all_u BLOCK LIST
258              
259             Returns a true value if all items in LIST meet the criterion given through
260             BLOCK. Sets C<$_> for each item in LIST in turn:
261              
262             print "All values are non-negative"
263             if all { $_ >= 0 } ($x, $y, $z);
264              
265             For an empty LIST, C returns true (i.e. no values failed the condition)
266             and C returns C.
267              
268             Thus, C<< all_u(@list) >> is equivalent to C<< @list ? all(@list) : undef >>.
269              
270             B: because Perl treats C as false, you must check the return value
271             of C with C or you will get the opposite result of what you
272             expect.
273              
274             =head3 any BLOCK LIST
275              
276             =head3 any_u BLOCK LIST
277              
278             Returns a true value if any item in LIST meets the criterion given through
279             BLOCK. Sets C<$_> for each item in LIST in turn:
280              
281             print "At least one non-negative value"
282             if any { $_ >= 0 } ($x, $y, $z);
283              
284             For an empty LIST, C returns false and C returns C.
285              
286             Thus, C<< any_u(@list) >> is equivalent to C<< @list ? any(@list) : undef >>.
287              
288             =head3 none BLOCK LIST
289              
290             =head3 none_u BLOCK LIST
291              
292             Logically the negation of C. Returns a true value if no item in LIST meets
293             the criterion given through BLOCK. Sets C<$_> for each item in LIST in turn:
294              
295             print "No non-negative values"
296             if none { $_ >= 0 } ($x, $y, $z);
297              
298             For an empty LIST, C returns true (i.e. no values failed the condition)
299             and C returns C.
300              
301             Thus, C<< none_u(@list) >> is equivalent to C<< @list ? none(@list) : undef >>.
302              
303             B: because Perl treats C as false, you must check the return value
304             of C with C or you will get the opposite result of what you
305             expect.
306              
307             =head3 notall BLOCK LIST
308              
309             =head3 notall_u BLOCK LIST
310              
311             Logically the negation of C. Returns a true value if not all items in LIST
312             meet the criterion given through BLOCK. Sets C<$_> for each item in LIST in
313             turn:
314              
315             print "Not all values are non-negative"
316             if notall { $_ >= 0 } ($x, $y, $z);
317              
318             For an empty LIST, C returns false and C returns C.
319              
320             Thus, C<< notall_u(@list) >> is equivalent to C<< @list ? notall(@list) : undef >>.
321              
322             =head3 one BLOCK LIST
323              
324             =head3 one_u BLOCK LIST
325              
326             Returns a true value if precisely one item in LIST meets the criterion
327             given through BLOCK. Sets C<$_> for each item in LIST in turn:
328              
329             print "Precisely one value defined"
330             if one { defined($_) } @list;
331              
332             Returns false otherwise.
333              
334             For an empty LIST, C returns false and C returns C.
335              
336             The expression C is almost equivalent to
337             C<1 == true BLOCK LIST>, except for short-cutting.
338             Evaluation of BLOCK will immediately stop at the second true value.
339              
340             =head2 Transformation
341              
342             =head3 apply BLOCK LIST
343              
344             Applies BLOCK to each item in LIST and returns a list of the values after BLOCK
345             has been applied. In scalar context, the last element is returned. This
346             function is similar to C but will not modify the elements of the input
347             list:
348              
349             my @list = (1 .. 4);
350             my @mult = apply { $_ *= 2 } @list;
351             print "\@list = @list\n";
352             print "\@mult = @mult\n";
353             __END__
354             @list = 1 2 3 4
355             @mult = 2 4 6 8
356              
357             Think of it as syntactic sugar for
358              
359             for (my @mult = @list) { $_ *= 2 }
360              
361             =head3 insert_after BLOCK VALUE LIST
362              
363             Inserts VALUE after the first item in LIST for which the criterion in BLOCK is
364             true. Sets C<$_> for each item in LIST in turn.
365              
366             my @list = qw/This is a list/;
367             insert_after { $_ eq "a" } "longer" => @list;
368             print "@list";
369             __END__
370             This is a longer list
371              
372             =head3 insert_after_string STRING VALUE LIST
373              
374             Inserts VALUE after the first item in LIST which is equal to STRING.
375              
376             my @list = qw/This is a list/;
377             insert_after_string "a", "longer" => @list;
378             print "@list";
379             __END__
380             This is a longer list
381              
382             =head3 pairwise BLOCK ARRAY1 ARRAY2
383              
384             Evaluates BLOCK for each pair of elements in ARRAY1 and ARRAY2 and returns a
385             new list consisting of BLOCK's return values. The two elements are set to C<$a>
386             and C<$b>. Note that those two are aliases to the original value so changing
387             them will modify the input arrays.
388              
389             @a = (1 .. 5);
390             @b = (11 .. 15);
391             @x = pairwise { $a + $b } @a, @b; # returns 12, 14, 16, 18, 20
392              
393             # mesh with pairwise
394             @a = qw/a b c/;
395             @b = qw/1 2 3/;
396             @x = pairwise { ($a, $b) } @a, @b; # returns a, 1, b, 2, c, 3
397              
398             =head3 mesh ARRAY1 ARRAY2 [ ARRAY3 ... ]
399              
400             =head3 zip ARRAY1 ARRAY2 [ ARRAY3 ... ]
401              
402             Returns a list consisting of the first elements of each array, then
403             the second, then the third, etc, until all arrays are exhausted.
404              
405             Examples:
406              
407             @x = qw/a b c d/;
408             @y = qw/1 2 3 4/;
409             @z = mesh @x, @y; # returns a, 1, b, 2, c, 3, d, 4
410              
411             @a = ('x');
412             @b = ('1', '2');
413             @c = qw/zip zap zot/;
414             @d = mesh @a, @b, @c; # x, 1, zip, undef, 2, zap, undef, undef, zot
415              
416             C is an alias for C.
417              
418             =head3 zip6
419              
420             =head3 zip_unflatten
421              
422             Returns a list of arrays consisting of the first elements of each array,
423             then the second, then the third, etc, until all arrays are exhausted.
424              
425             @x = qw/a b c d/;
426             @y = qw/1 2 3 4/;
427             @z = zip6 @x, @y; # returns [a, 1], [b, 2], [c, 3], [d, 4]
428              
429             @a = ('x');
430             @b = ('1', '2');
431             @c = qw/zip zap zot/;
432             @d = zip6 @a, @b, @c; # [x, 1, zip], [undef, 2, zap], [undef, undef, zot]
433              
434             C is an alias for C.
435              
436             =head3 listcmp ARRAY0 ARRAY1 [ ARRAY2 ... ]
437              
438             Returns an associative list of elements and every I of the list it
439             was found in. Allowes easy implementation of @a & @b, @a | @b, @a ^ @b and
440             so on.
441             Undefined entries in any given array are skipped.
442              
443             my @a = qw(one two three four five six seven eight nine ten eleven twelve thirteen);
444             my @b = qw(two three five seven eleven thirteen seventeen);
445             my @c = qw(one one two three five eight thirteen twentyone);
446             my %cmp = listcmp @a, @b, @c; # returns (one => [0, 2], two => [0, 1, 2], three => [0, 1, 2], four => [0], ...)
447              
448             my @seq = (1, 2, 3);
449             my @prim = (undef, 2, 3, 5);
450             my @fib = (1, 1, 2);
451             my $cmp = listcmp @seq, @prim, @fib;
452             # returns { 1 => [0, 2], 2 => [0, 1, 2], 3 => [0, 1], 5 => [1] }
453              
454             =head3 arrayify LIST[,LIST[,LIST...]]
455              
456             Returns a list costisting of each element of given arrays. Recursive arrays
457             are flattened, too.
458              
459             @a = (1, [[2], 3], 4, [5], 6, [7], 8, 9);
460             @l = arrayify @a; # returns 1, 2, 3, 4, 5, 6, 7, 8, 9
461              
462             =head3 uniq LIST
463              
464             =head3 distinct LIST
465              
466             Returns a new list by stripping duplicate values in LIST by comparing
467             the values as hash keys, except that undef is considered separate from ''.
468             The order of elements in the returned list is the same as in LIST. In
469             scalar context, returns the number of unique elements in LIST.
470              
471             my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 1 2 3 5 4
472             my $x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 5
473             # returns "Mike", "Michael", "Richard", "Rick"
474             my @n = distinct "Mike", "Michael", "Richard", "Rick", "Michael", "Rick"
475             # returns "A8", "", undef, "A5", "S1"
476             my @s = distinct "A8", "", undef, "A5", "S1", "A5", "A8"
477             # returns "Giulia", "Giulietta", undef, "", 156, "GTA", "GTV", 159, "Brera", "4C"
478             my @w = uniq "Giulia", "Giulietta", undef, "", 156, "GTA", "GTV", 159, "Brera", "4C", "Giulietta", "Giulia"
479              
480             C is an alias for C.
481              
482             B can be used to give feedback about this behavior.
483              
484             =head3 singleton LIST
485              
486             Returns a new list by stripping values in LIST occurring more than once by
487             comparing the values as hash keys, except that undef is considered separate
488             from ''. The order of elements in the returned list is the same as in LIST.
489             In scalar context, returns the number of elements occurring only once in LIST.
490              
491             my @x = singleton 1,1,2,2,3,4,5 # returns 3 4 5
492              
493             =head3 duplicates LIST
494              
495             Returns a new list by stripping values in LIST occuring less than twice by
496             comparing the values as hash keys, except that undef is considered separate
497             from ''. The order of elements in the returned list is the same as in LIST.
498             In scalar context, returns the number of elements occurring only once in LIST.
499              
500             my @y = duplicates 1,1,2,4,7,2,3,4,6,9; #returns 1,2,4
501              
502             =head3 frequency LIST
503              
504             Returns an associative list of distinct values and the corresponding frequency.
505              
506             my @f = frequency values %radio_nrw; # returns (
507             # 'Deutschlandfunk (DLF)' => 9, 'WDR 3' => 10,
508             # 'WDR 4' => 11, 'WDR 5' => 14, 'WDR Eins Live' => 14,
509             # 'Deutschlandradio Kultur' => 8,...)
510              
511             =head3 occurrences LIST
512              
513             Returns a new list of frequencies and the corresponding values from LIST.
514              
515             my @o = occurrences ((1) x 3, (2) x 4, (3) x 2, (4) x 7, (5) x 2, (6) x 4);
516             # @o = (undef, undef, [3, 5], [1], [2, 6], undef, undef, [4]);
517              
518             =head3 mode LIST
519              
520             Returns the modal value of LIST. In scalar context, just the modal value
521             is returned, in list context all probes occuring I times are returned,
522             too.
523              
524             my @m = mode ((1) x 3, (2) x 4, (3) x 2, (4) x 7, (5) x 2, (6) x 4, (7) x 3, (8) x 7);
525             # @m = (7, 4, 8) - bimodal LIST
526              
527             =head2 Partitioning
528              
529             =head3 after BLOCK LIST
530              
531             Returns a list of the values of LIST after (and not including) the point
532             where BLOCK returns a true value. Sets C<$_> for each element in LIST in turn.
533              
534             @x = after { $_ % 5 == 0 } (1..9); # returns 6, 7, 8, 9
535              
536             =head3 after_incl BLOCK LIST
537              
538             Same as C but also includes the element for which BLOCK is true.
539              
540             =head3 before BLOCK LIST
541              
542             Returns a list of values of LIST up to (and not including) the point where BLOCK
543             returns a true value. Sets C<$_> for each element in LIST in turn.
544              
545             =head3 before_incl BLOCK LIST
546              
547             Same as C but also includes the element for which BLOCK is true.
548              
549             =head3 part BLOCK LIST
550              
551             Partitions LIST based on the return value of BLOCK which denotes into which
552             partition the current value is put.
553              
554             Returns a list of the partitions thusly created. Each partition created is a
555             reference to an array.
556              
557             my $i = 0;
558             my @part = part { $i++ % 2 } 1 .. 8; # returns [1, 3, 5, 7], [2, 4, 6, 8]
559              
560             You can have a sparse list of partitions as well where non-set partitions will
561             be undef:
562              
563             my @part = part { 2 } 1 .. 10; # returns undef, undef, [ 1 .. 10 ]
564              
565             Be careful with negative values, though:
566              
567             my @part = part { -1 } 1 .. 10;
568             __END__
569             Modification of non-creatable array value attempted, subscript -1 ...
570              
571             Negative values are only ok when they refer to a partition previously created:
572              
573             my @idx = ( 0, 1, -1 );
574             my $i = 0;
575             my @part = part { $idx[$++ % 3] } 1 .. 8; # [1, 4, 7], [2, 3, 5, 6, 8]
576              
577             =head3 samples COUNT LIST
578              
579             Returns a new list containing COUNT random samples from LIST. Is similar to
580             L, but stops after COUNT.
581              
582             @r = samples 10, 1..10; # same as shuffle
583             @r2 = samples 5, 1..10; # gives 5 values from 1..10;
584              
585             =head2 Iteration
586              
587             =head3 each_array ARRAY1 ARRAY2 ...
588              
589             Creates an array iterator to return the elements of the list of arrays ARRAY1,
590             ARRAY2 throughout ARRAYn in turn. That is, the first time it is called, it
591             returns the first element of each array. The next time, it returns the second
592             elements. And so on, until all elements are exhausted.
593              
594             This is useful for looping over more than one array at once:
595              
596             my $ea = each_array(@a, @b, @c);
597             while ( my ($a, $b, $c) = $ea->() ) { .... }
598              
599             The iterator returns the empty list when it reached the end of all arrays.
600              
601             If the iterator is passed an argument of 'C', then it returns
602             the index of the last fetched set of values, as a scalar.
603              
604             =head3 each_arrayref LIST
605              
606             Like each_array, but the arguments are references to arrays, not the
607             plain arrays.
608              
609             =head3 natatime EXPR, LIST
610              
611             Creates an array iterator, for looping over an array in chunks of
612             C<$n> items at a time. (n at a time, get it?). An example is
613             probably a better explanation than I could give in words.
614              
615             Example:
616              
617             my @x = ('a' .. 'g');
618             my $it = natatime 3, @x;
619             while (my @vals = $it->())
620             {
621             print "@vals\n";
622             }
623              
624             This prints
625              
626             a b c
627             d e f
628             g
629              
630             =head2 Searching
631              
632             =head3 firstval BLOCK LIST
633              
634             =head3 first_value BLOCK LIST
635              
636             Returns the first element in LIST for which BLOCK evaluates to true. Each
637             element of LIST is set to C<$_> in turn. Returns C if no such element
638             has been found.
639              
640             C is an alias for C.
641              
642             =head3 onlyval BLOCK LIST
643              
644             =head3 only_value BLOCK LIST
645              
646             Returns the only element in LIST for which BLOCK evaluates to true. Sets
647             C<$_> for each item in LIST in turn. Returns C if no such element
648             has been found.
649              
650             C is an alias for C.
651              
652             =head3 lastval BLOCK LIST
653              
654             =head3 last_value BLOCK LIST
655              
656             Returns the last value in LIST for which BLOCK evaluates to true. Each element
657             of LIST is set to C<$_> in turn. Returns C if no such element has been
658             found.
659              
660             C is an alias for C.
661              
662             =head3 firstres BLOCK LIST
663              
664             =head3 first_result BLOCK LIST
665              
666             Returns the result of BLOCK for the first element in LIST for which BLOCK
667             evaluates to true. Each element of LIST is set to C<$_> in turn. Returns
668             C if no such element has been found.
669              
670             C is an alias for C.
671              
672             =head3 onlyres BLOCK LIST
673              
674             =head3 only_result BLOCK LIST
675              
676             Returns the result of BLOCK for the first element in LIST for which BLOCK
677             evaluates to true. Sets C<$_> for each item in LIST in turn. Returns
678             C if no such element has been found.
679              
680             C is an alias for C.
681              
682             =head3 lastres BLOCK LIST
683              
684             =head3 last_result BLOCK LIST
685              
686             Returns the result of BLOCK for the last element in LIST for which BLOCK
687             evaluates to true. Each element of LIST is set to C<$_> in turn. Returns
688             C if no such element has been found.
689              
690             C is an alias for C.
691              
692             =head3 indexes BLOCK LIST
693              
694             Evaluates BLOCK for each element in LIST (assigned to C<$_>) and returns a list
695             of the indices of those elements for which BLOCK returned a true value. This is
696             just like C only that it returns indices instead of values:
697              
698             @x = indexes { $_ % 2 == 0 } (1..10); # returns 1, 3, 5, 7, 9
699              
700             =head3 firstidx BLOCK LIST
701              
702             =head3 first_index BLOCK LIST
703              
704             Returns the index of the first element in LIST for which the criterion in BLOCK
705             is true. Sets C<$_> for each item in LIST in turn:
706              
707             my @list = (1, 4, 3, 2, 4, 6);
708             printf "item with index %i in list is 4", firstidx { $_ == 4 } @list;
709             __END__
710             item with index 1 in list is 4
711              
712             Returns C<-1> if no such item could be found.
713              
714             C is an alias for C.
715              
716             =head3 onlyidx BLOCK LIST
717              
718             =head3 only_index BLOCK LIST
719              
720             Returns the index of the only element in LIST for which the criterion
721             in BLOCK is true. Sets C<$_> for each item in LIST in turn:
722              
723             my @list = (1, 3, 4, 3, 2, 4);
724             printf "uniqe index of item 2 in list is %i", onlyidx { $_ == 2 } @list;
725             __END__
726             unique index of item 2 in list is 4
727              
728             Returns C<-1> if either no such item or more than one of these
729             has been found.
730              
731             C is an alias for C.
732              
733             =head3 lastidx BLOCK LIST
734              
735             =head3 last_index BLOCK LIST
736              
737             Returns the index of the last element in LIST for which the criterion in BLOCK
738             is true. Sets C<$_> for each item in LIST in turn:
739              
740             my @list = (1, 4, 3, 2, 4, 6);
741             printf "item with index %i in list is 4", lastidx { $_ == 4 } @list;
742             __END__
743             item with index 4 in list is 4
744              
745             Returns C<-1> if no such item could be found.
746              
747             C is an alias for C.
748              
749             =head2 Sorting
750              
751             =head3 sort_by BLOCK LIST
752              
753             Returns the list of values sorted according to the string values returned by the
754             KEYFUNC block or function. A typical use of this may be to sort objects according
755             to the string value of some accessor, such as
756              
757             sort_by { $_->name } @people
758              
759             The key function is called in scalar context, being passed each value in turn as
760             both $_ and the only argument in the parameters, @_. The values are then sorted
761             according to string comparisons on the values returned.
762             This is equivalent to
763              
764             sort { $a->name cmp $b->name } @people
765              
766             except that it guarantees the name accessor will be executed only once per value.
767             One interesting use-case is to sort strings which may have numbers embedded in them
768             "naturally", rather than lexically.
769              
770             sort_by { s/(\d+)/sprintf "%09d", $1/eg; $_ } @strings
771              
772             This sorts strings by generating sort keys which zero-pad the embedded numbers to
773             some level (9 digits in this case), helping to ensure the lexical sort puts them
774             in the correct order.
775              
776             =head3 nsort_by BLOCK LIST
777              
778             Similar to sort_by but compares its key values numerically.
779              
780             =head3 qsort BLOCK ARRAY
781              
782             This sorts the given array B using the given compare code. Except for
783             tiny compare code like C<< $a <=> $b >>, qsort is much faster than Perl's C
784             depending on the version.
785              
786             Compared 5.8 and 5.26:
787              
788             my @rl;
789             for(my $i = 0; $i < 1E6; ++$i) { push @rl, rand(1E5) }
790             my $idx;
791              
792             sub ext_cmp { $_[0] <=> $_[1] }
793              
794             cmpthese( -60, {
795             'qsort' => sub {
796             my @qrl = @rl;
797             qsort { ext_cmp($a, $b) } @qrl;
798             $idx = bsearchidx { ext_cmp($_, $rl[0]) } @qrl
799             },
800             'reverse qsort' => sub {
801             my @qrl = @rl;
802             qsort { ext_cmp($b, $a) } @qrl;
803             $idx = bsearchidx { ext_cmp($rl[0], $_) } @qrl
804             },
805             'sort' => sub {
806             my @srl = @rl;
807             @srl = sort { ext_cmp($a, $b) } @srl;
808             $idx = bsearchidx { ext_cmp($_, $rl[0]) } @srl
809             },
810             'reverse sort' => sub {
811             my @srl = @rl;
812             @srl = sort { ext_cmp($b, $a) } @srl;
813             $idx = bsearchidx { ext_cmp($rl[0], $_) } @srl
814             },
815             });
816              
817             5.8 results
818              
819             s/iter reverse sort sort reverse qsort qsort
820             reverse sort 6.21 -- -0% -8% -10%
821             sort 6.19 0% -- -7% -10%
822             reverse qsort 5.73 8% 8% -- -2%
823             qsort 5.60 11% 11% 2% --
824              
825             5.26 results
826              
827             s/iter reverse sort sort reverse qsort qsort
828             reverse sort 4.54 -- -0% -96% -96%
829             sort 4.52 0% -- -96% -96%
830             reverse qsort 0.203 2139% 2131% -- -19%
831             qsort 0.164 2666% 2656% 24% --
832              
833             Use it where external data sources might have to be compared (think of L
834             "tables").
835              
836             C is available from List::MoreUtils::XS only. It's insane to maintain
837             a wrapper around Perl's sort nor having a pure Perl implementation. One could
838             create a flip-book in same speed as PP runs a qsort.
839              
840             =head2 Searching in sorted Lists
841              
842             =head3 bsearch BLOCK LIST
843              
844             Performs a binary search on LIST which must be a sorted list of values. BLOCK
845             must return a negative value if the current element (stored in C<$_>) is smaller,
846             a positive value if it is bigger and zero if it matches.
847              
848             Returns a boolean value in scalar context. In list context, it returns the element
849             if it was found, otherwise the empty list.
850              
851             =head3 bsearchidx BLOCK LIST
852              
853             =head3 bsearch_index BLOCK LIST
854              
855             Performs a binary search on LIST which must be a sorted list of values. BLOCK
856             must return a negative value if the current element (stored in C<$_>) is smaller,
857             a positive value if it is bigger and zero if it matches.
858              
859             Returns the index of found element, otherwise C<-1>.
860              
861             C is an alias for C.
862              
863             =head3 lower_bound BLOCK LIST
864              
865             Returns the index of the first element in LIST which does not compare
866             I. Technically it's the first element in LIST which does
867             not return a value below zero when passed to BLOCK.
868              
869             @ids = (1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 11, 13, 13, 13, 17);
870             $lb = lower_bound { $_ <=> 2 } @ids; # returns 2
871             $lb = lower_bound { $_ <=> 4 } @ids; # returns 10
872              
873             lower_bound has a complexity of O(log n).
874              
875             =head3 upper_bound BLOCK LIST
876              
877             Returns the index of the first element in LIST which does not compare
878             I. Technically it's the first element in LIST which does
879             not return a value below or equal to zero when passed to BLOCK.
880              
881             @ids = (1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 11, 13, 13, 13, 17);
882             $lb = upper_bound { $_ <=> 2 } @ids; # returns 4
883             $lb = upper_bound { $_ <=> 4 } @ids; # returns 14
884              
885             upper_bound has a complexity of O(log n).
886              
887             =head3 equal_range BLOCK LIST
888              
889             Returns a pair of indices containing the lower_bound and the upper_bound.
890              
891             =head2 Operations on sorted Lists
892              
893             =head3 binsert BLOCK ITEM LIST
894              
895             =head3 bsearch_insert BLOCK ITEM LIST
896              
897             Performs a binary search on LIST which must be a sorted list of values. BLOCK
898             must return a negative value if the current element (stored in C<$_>) is smaller,
899             a positive value if it is bigger and zero if it matches.
900              
901             ITEM is inserted at the index where the ITEM should be placed (based on above
902             search). That means, it's inserted before the next bigger element.
903              
904             @l = (2,3,5,7);
905             binsert { $_ <=> 4 } 4, @l; # @l = (2,3,4,5,7)
906             binsert { $_ <=> 6 } 42, @l; # @l = (2,3,4,42,7)
907              
908             You take care that the inserted element matches the compare result.
909              
910             =head3 bremove BLOCK LIST
911              
912             =head3 bsearch_remove BLOCK LIST
913              
914             Performs a binary search on LIST which must be a sorted list of values. BLOCK
915             must return a negative value if the current element (stored in C<$_>) is smaller,
916             a positive value if it is bigger and zero if it matches.
917              
918             The item at the found position is removed and returned.
919              
920             @l = (2,3,4,5,7);
921             bremove { $_ <=> 4 }, @l; # @l = (2,3,5,7);
922              
923             =head2 Counting and calculation
924              
925             =head3 true BLOCK LIST
926              
927             Counts the number of elements in LIST for which the criterion in BLOCK is true.
928             Sets C<$_> for each item in LIST in turn:
929              
930             printf "%i item(s) are defined", true { defined($_) } @list;
931              
932             =head3 false BLOCK LIST
933              
934             Counts the number of elements in LIST for which the criterion in BLOCK is false.
935             Sets C<$_> for each item in LIST in turn:
936              
937             printf "%i item(s) are not defined", false { defined($_) } @list;
938              
939             =head3 reduce_0 BLOCK LIST
940              
941             Reduce LIST by calling BLOCK in scalar context for each element of LIST.
942             C<$a> contains the progressional result and is initialized with 0.
943             C<$b> contains the current processed element of LIST and C<$_> contains the
944             index of the element in C<$b>.
945              
946             The idea behind reduce_0 is B (addition of a sequence of numbers).
947              
948             =head3 reduce_1 BLOCK LIST
949              
950             Reduce LIST by calling BLOCK in scalar context for each element of LIST.
951             C<$a> contains the progressional result and is initialized with 1.
952             C<$b> contains the current processed element of LIST and C<$_> contains the
953             index of the element in C<$b>.
954              
955             The idea behind reduce_1 is product of a sequence of numbers.
956              
957             =head3 reduce_u BLOCK LIST
958              
959             Reduce LIST by calling BLOCK in scalar context for each element of LIST.
960             C<$a> contains the progressional result and is initialized with 1.
961             C<$b> contains the current processed element of LIST and C<$_> contains the
962             index of the element in C<$b>.
963              
964             This function has been added if one might need the extra of the index
965             value but need an individual initialization.
966              
967             B: In most cases L will do the
968             job better.
969              
970             =head3 minmax LIST
971              
972             Calculates the minimum and maximum of LIST and returns a two element list with
973             the first element being the minimum and the second the maximum. Returns the
974             empty list if LIST was empty.
975              
976             The C algorithm differs from a naive iteration over the list where each
977             element is compared to two values being the so far calculated min and max value
978             in that it only requires 3n/2 - 2 comparisons. Thus it is the most efficient
979             possible algorithm.
980              
981             However, the Perl implementation of it has some overhead simply due to the fact
982             that there are more lines of Perl code involved. Therefore, LIST needs to be
983             fairly big in order for C to win over a naive implementation. This
984             limitation does not apply to the XS version.
985              
986             =head3 minmaxstr LIST
987              
988             Computes the minimum and maximum of LIST using string compare and returns a
989             two element list with the first element being the minimum and the second the
990             maximum. Returns the empty list if LIST was empty.
991              
992             The implementation is similar to C.
993              
994             =head1 ENVIRONMENT
995              
996             When C is set, the module will always use the pure-Perl
997             implementation and not the XS one. This environment variable is really just
998             there for the test-suite to force testing the Perl implementation, and possibly
999             for reporting of bugs. I don't see any reason to use it in a production
1000             environment.
1001              
1002             =head1 MAINTENANCE
1003              
1004             The maintenance goal is to preserve the documented semantics of the API;
1005             bug fixes that bring actual behavior in line with semantics are allowed.
1006             New API functions may be added over time. If a backwards incompatible
1007             change is unavoidable, we will attempt to provide support for the legacy
1008             API using the same export tag mechanism currently in place.
1009              
1010             This module attempts to use few non-core dependencies. Non-core
1011             configuration and testing modules will be bundled when reasonable;
1012             run-time dependencies will be added only if they deliver substantial
1013             benefit.
1014              
1015             =head1 CONTRIBUTING
1016              
1017             While contributions are appreciated, a contribution should not cause more
1018             effort for the maintainer than the contribution itself saves (see
1019             L).
1020              
1021             To get more familiar where help could be needed - see L.
1022              
1023             =head1 BUGS
1024              
1025             There is a problem with a bug in 5.6.x perls. It is a syntax error to write
1026             things like:
1027              
1028             my @x = apply { s/foo/bar/ } qw{ foo bar baz };
1029              
1030             It has to be written as either
1031              
1032             my @x = apply { s/foo/bar/ } 'foo', 'bar', 'baz';
1033              
1034             or
1035              
1036             my @x = apply { s/foo/bar/ } my @dummy = qw/foo bar baz/;
1037              
1038             Perl 5.5.x and Perl 5.8.x don't suffer from this limitation.
1039              
1040             If you have a functionality that you could imagine being in this module, please
1041             drop me a line. This module's policy will be less strict than L's
1042             when it comes to additions as it isn't a core module.
1043              
1044             When you report bugs, it would be nice if you could additionally give me the
1045             output of your program with the environment variable C set
1046             to a true value. That way I know where to look for the problem (in XS,
1047             pure-Perl or possibly both).
1048              
1049             =head1 SUPPORT
1050              
1051             Bugs should always be submitted via the CPAN bug tracker.
1052              
1053             You can find documentation for this module with the perldoc command.
1054              
1055             perldoc List::MoreUtils
1056              
1057             You can also look for information at:
1058              
1059             =over 4
1060              
1061             =item * RT: CPAN's request tracker
1062              
1063             L
1064              
1065             =item * AnnoCPAN: Annotated CPAN documentation
1066              
1067             L
1068              
1069             =item * CPAN Ratings
1070              
1071             L
1072              
1073             =item * MetaCPAN
1074              
1075             L
1076              
1077             =item * CPAN Search
1078              
1079             L
1080              
1081             =item * Git Repository
1082              
1083             L
1084              
1085             =back
1086              
1087             =head2 Where can I go for help?
1088              
1089             If you have a bug report, a patch or a suggestion, please open a new
1090             report ticket at CPAN (but please check previous reports first in case
1091             your issue has already been addressed) or open an issue on GitHub.
1092              
1093             Report tickets should contain a detailed description of the bug or
1094             enhancement request and at least an easily verifiable way of
1095             reproducing the issue or fix. Patches are always welcome, too - and
1096             it's cheap to send pull-requests on GitHub. Please keep in mind that
1097             code changes are more likely accepted when they're bundled with an
1098             approving test.
1099              
1100             If you think you've found a bug then please read
1101             "How to Report Bugs Effectively" by Simon Tatham:
1102             L.
1103              
1104             =head2 Where can I go for help with a concrete version?
1105              
1106             Bugs and feature requests are accepted against the latest version
1107             only. To get patches for earlier versions, you need to get an
1108             agreement with a developer of your choice - who may or not report the
1109             issue and a suggested fix upstream (depends on the license you have
1110             chosen).
1111              
1112             =head2 Business support and maintenance
1113              
1114             Generally, in volunteered projects, there is no right for support.
1115             While every maintainer is happy to improve the provided software,
1116             spare time is limited.
1117              
1118             For those who have a use case which requires guaranteed support, one of
1119             the maintainers should be hired or contracted. For business support you
1120             can contact Jens via his CPAN email address rehsackATcpan.org. Please
1121             keep in mind that business support is neither available for free nor
1122             are you eligible to receive any support based on the license distributed
1123             with this package.
1124              
1125             =head1 THANKS
1126              
1127             =head2 Tassilo von Parseval
1128              
1129             Credits go to a number of people: Steve Purkis for giving me namespace advice
1130             and James Keenan and Terrence Branno for their effort of keeping the CPAN
1131             tidier by making L obsolete.
1132              
1133             Brian McCauley suggested the inclusion of apply() and provided the pure-Perl
1134             implementation for it.
1135              
1136             Eric J. Roode asked me to add all functions from his module C
1137             into this one. With minor modifications, the pure-Perl implementations of those
1138             are by him.
1139              
1140             The bunch of people who almost immediately pointed out the many problems with
1141             the glitchy 0.07 release (Slaven Rezic, Ron Savage, CPAN testers).
1142              
1143             A particularly nasty memory leak was spotted by Thomas A. Lowery.
1144              
1145             Lars Thegler made me aware of problems with older Perl versions.
1146              
1147             Anno Siegel de-orphaned each_arrayref().
1148              
1149             David Filmer made me aware of a problem in each_arrayref that could ultimately
1150             lead to a segfault.
1151              
1152             Ricardo Signes suggested the inclusion of part() and provided the
1153             Perl-implementation.
1154              
1155             Robin Huston kindly fixed a bug in perl's MULTICALL API to make the
1156             XS-implementation of part() work.
1157              
1158             =head2 Jens Rehsack
1159              
1160             Credits goes to all people contributing feedback during the v0.400
1161             development releases.
1162              
1163             Special thanks goes to David Golden who spent a lot of effort to develop
1164             a design to support current state of CPAN as well as ancient software
1165             somewhere in the dark. He also contributed a lot of patches to refactor
1166             the API frontend to welcome any user of List::MoreUtils - from ancient
1167             past to recently last used.
1168              
1169             Toby Inkster provided a lot of useful feedback for sane importer code
1170             and was a nice sounding board for API discussions.
1171              
1172             Peter Rabbitson provided a sane git repository setup containing entire
1173             package history.
1174              
1175             =head1 TODO
1176              
1177             A pile of requests from other people is still pending further processing in
1178             my mailbox. This includes:
1179              
1180             =over 4
1181              
1182             =item * delete_index
1183              
1184             =item * random_item
1185              
1186             =item * random_item_delete_index
1187              
1188             =item * list_diff_hash
1189              
1190             =item * list_diff_inboth
1191              
1192             =item * list_diff_infirst
1193              
1194             =item * list_diff_insecond
1195              
1196             These were all suggested by Dan Muey.
1197              
1198             =item * listify
1199              
1200             Always return a flat list when either a simple scalar value was passed or an
1201             array-reference. Suggested by Mark Summersault.
1202              
1203             =back
1204              
1205             =head1 SEE ALSO
1206              
1207             L, L, L
1208              
1209             =head1 AUTHOR
1210              
1211             Jens Rehsack Erehsack AT cpan.orgE
1212              
1213             Adam Kennedy Eadamk@cpan.orgE
1214              
1215             Tassilo von Parseval Etassilo.von.parseval@rwth-aachen.deE
1216              
1217             =head1 COPYRIGHT AND LICENSE
1218              
1219             Some parts copyright 2011 Aaron Crane.
1220              
1221             Copyright 2004 - 2010 by Tassilo von Parseval
1222              
1223             Copyright 2013 - 2017 by Jens Rehsack
1224              
1225             All code added with 0.417 or later is licensed under the Apache License,
1226             Version 2.0 (the "License"); you may not use this file except in compliance
1227             with the License. You may obtain a copy of the License at
1228              
1229             http://www.apache.org/licenses/LICENSE-2.0
1230              
1231             Unless required by applicable law or agreed to in writing, software
1232             distributed under the License is distributed on an "AS IS" BASIS,
1233             WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1234             See the License for the specific language governing permissions and
1235             limitations under the License.
1236              
1237             All code until 0.416 is licensed under the same terms as Perl itself,
1238             either Perl version 5.8.4 or, at your option, any later version of
1239             Perl 5 you may have available.
1240              
1241             =cut
1242              
1243             1;