1List::MoreUtils(3)    User Contributed Perl Documentation   List::MoreUtils(3)
2
3
4

NAME

6       List::MoreUtils - Provide the stuff missing in List::Util
7

SYNOPSIS

9           # import specific functions
10
11           use List::MoreUtils qw(any uniq);
12
13           if ( any { /foo/ } uniq @has_duplicates ) {
14               # do stuff
15           }
16
17           # import everything
18
19           use List::MoreUtils ':all';
20
21           # import by API
22
23           # has "original" any/all/none/notall behavior
24           use List::MoreUtils ':like_0.22';
25           # 0.22 + bsearch
26           use List::MoreUtils ':like_0.24';
27           # has "simplified" any/all/none/notall behavior + (n)sort_by
28           use List::MoreUtils ':like_0.33';
29

DESCRIPTION

31       List::MoreUtils provides some trivial but commonly needed functionality
32       on lists which is not going to go into List::Util.
33
34       All of the below functions are implementable in only a couple of lines
35       of Perl code. Using the functions from this module however should give
36       slightly better performance as everything is implemented in C. The
37       pure-Perl implementation of these functions only serves as a fallback
38       in case the C portions of this module couldn't be compiled on this
39       machine.
40

EXPORTS

42   Default behavior
43       Nothing by default. To import all of this module's symbols use the
44       ":all" tag.  Otherwise functions can be imported by name as usual:
45
46           use List::MoreUtils ':all';
47
48           use List::MoreUtils qw{ any firstidx };
49
50       Because historical changes to the API might make upgrading
51       List::MoreUtils difficult for some projects, the legacy API is
52       available via special import tags.
53
54   Like version 0.22 (last release with original API)
55       This API was available from 2006 to 2009, returning undef for empty
56       lists on "all"/"any"/"none"/"notall":
57
58           use List::MoreUtils ':like_0.22';
59
60       This import tag will import all functions available as of version 0.22.
61       However, it will import "any_u" as "any", "all_u" as "all", "none_u" as
62       "none", and "notall_u" as "notall".
63
64   Like version 0.24 (first incompatible change)
65       This API was available from 2010 to 2011.  It changed the return value
66       of "none" and added the "bsearch" function.
67
68           use List::MoreUtils ':like_0.24';
69
70       This import tag will import all functions available as of version 0.24.
71       However it will import "any_u" as "any", "all_u" as "all", and
72       "notall_u" as "notall".  It will import "none" as described in the
73       documentation below (true for empty list).
74
75   Like version 0.33 (second incompatible change)
76       This API was available from 2011 to 2014. It is widely used in several
77       CPAN modules and thus it's closest to the current API.  It changed the
78       return values of "any", "all", and "notall".  It added the "sort_by"
79       and "nsort_by" functions and the "distinct" alias for "uniq".  It
80       omitted "bsearch".
81
82           use List::MoreUtils ':like_0.33';
83
84       This import tag will import all functions available as of version 0.33.
85       Note: it will not import "bsearch" for consistency with the 0.33 API.
86

FUNCTIONS

88   Junctions
89       Treatment of an empty list
90
91       There are two schools of thought for how to evaluate a junction on an
92       empty list:
93
94       ·   Reduction to an identity (boolean)
95
96       ·   Result is undefined (three-valued)
97
98       In the first case, the result of the junction applied to the empty list
99       is determined by a mathematical reduction to an identity depending on
100       whether the underlying comparison is "or" or "and".  Conceptually:
101
102                           "any are true"      "all are true"
103                           --------------      --------------
104           2 elements:     A || B || 0         A && B && 1
105           1 element:      A || 0              A && 1
106           0 elements:     0                   1
107
108       In the second case, three-value logic is desired, in which a junction
109       applied to an empty list returns "undef" rather than true or false
110
111       Junctions with a "_u" suffix implement three-valued logic.  Those
112       without are boolean.
113
114       all BLOCK LIST
115
116       all_u BLOCK LIST
117
118       Returns a true value if all items in LIST meet the criterion given
119       through BLOCK. Sets $_ for each item in LIST in turn:
120
121         print "All values are non-negative"
122           if all { $_ >= 0 } ($x, $y, $z);
123
124       For an empty LIST, "all" returns true (i.e. no values failed the
125       condition) and "all_u" returns "undef".
126
127       Thus, "all_u(@list)" is equivalent to "@list ? all(@list) : undef".
128
129       Note: because Perl treats "undef" as false, you must check the return
130       value of "all_u" with "defined" or you will get the opposite result of
131       what you expect.
132
133       any BLOCK LIST
134
135       any_u BLOCK LIST
136
137       Returns a true value if any item in LIST meets the criterion given
138       through BLOCK. Sets $_ for each item in LIST in turn:
139
140         print "At least one non-negative value"
141           if any { $_ >= 0 } ($x, $y, $z);
142
143       For an empty LIST, "any" returns false and "any_u" returns "undef".
144
145       Thus, "any_u(@list)" is equivalent to "@list ? any(@list) : undef".
146
147       none BLOCK LIST
148
149       none_u BLOCK LIST
150
151       Logically the negation of "any". Returns a true value if no item in
152       LIST meets the criterion given through BLOCK. Sets $_ for each item in
153       LIST in turn:
154
155         print "No non-negative values"
156           if none { $_ >= 0 } ($x, $y, $z);
157
158       For an empty LIST, "none" returns true (i.e. no values failed the
159       condition) and "none_u" returns "undef".
160
161       Thus, "none_u(@list)" is equivalent to "@list ? none(@list) : undef".
162
163       Note: because Perl treats "undef" as false, you must check the return
164       value of "none_u" with "defined" or you will get the opposite result of
165       what you expect.
166
167       notall BLOCK LIST
168
169       notall_u BLOCK LIST
170
171       Logically the negation of "all". Returns a true value if not all items
172       in LIST meet the criterion given through BLOCK. Sets $_ for each item
173       in LIST in turn:
174
175         print "Not all values are non-negative"
176           if notall { $_ >= 0 } ($x, $y, $z);
177
178       For an empty LIST, "notall" returns false and "notall_u" returns
179       "undef".
180
181       Thus, "notall_u(@list)" is equivalent to "@list ? notall(@list) :
182       undef".
183
184       one BLOCK LIST
185
186       one_u BLOCK LIST
187
188       Returns a true value if precisely one item in LIST meets the criterion
189       given through BLOCK. Sets $_ for each item in LIST in turn:
190
191           print "Precisely one value defined"
192               if one { defined($_) } @list;
193
194       Returns false otherwise.
195
196       For an empty LIST, "one" returns false and "one_u" returns "undef".
197
198       The expression "one BLOCK LIST" is almost equivalent to "1 == true
199       BLOCK LIST", except for short-cutting.  Evaluation of BLOCK will
200       immediately stop at the second true value.
201
202   Transformation
203       apply BLOCK LIST
204
205       Applies BLOCK to each item in LIST and returns a list of the values
206       after BLOCK has been applied. In scalar context, the last element is
207       returned.  This function is similar to "map" but will not modify the
208       elements of the input list:
209
210         my @list = (1 .. 4);
211         my @mult = apply { $_ *= 2 } @list;
212         print "\@list = @list\n";
213         print "\@mult = @mult\n";
214         __END__
215         @list = 1 2 3 4
216         @mult = 2 4 6 8
217
218       Think of it as syntactic sugar for
219
220         for (my @mult = @list) { $_ *= 2 }
221
222       insert_after BLOCK VALUE LIST
223
224       Inserts VALUE after the first item in LIST for which the criterion in
225       BLOCK is true. Sets $_ for each item in LIST in turn.
226
227         my @list = qw/This is a list/;
228         insert_after { $_ eq "a" } "longer" => @list;
229         print "@list";
230         __END__
231         This is a longer list
232
233       insert_after_string STRING VALUE LIST
234
235       Inserts VALUE after the first item in LIST which is equal to STRING.
236
237         my @list = qw/This is a list/;
238         insert_after_string "a", "longer" => @list;
239         print "@list";
240         __END__
241         This is a longer list
242
243       pairwise BLOCK ARRAY1 ARRAY2
244
245       Evaluates BLOCK for each pair of elements in ARRAY1 and ARRAY2 and
246       returns a new list consisting of BLOCK's return values. The two
247       elements are set to $a and $b.  Note that those two are aliases to the
248       original value so changing them will modify the input arrays.
249
250         @a = (1 .. 5);
251         @b = (11 .. 15);
252         @x = pairwise { $a + $b } @a, @b;     # returns 12, 14, 16, 18, 20
253
254         # mesh with pairwise
255         @a = qw/a b c/;
256         @b = qw/1 2 3/;
257         @x = pairwise { ($a, $b) } @a, @b;    # returns a, 1, b, 2, c, 3
258
259       mesh ARRAY1 ARRAY2 [ ARRAY3 ... ]
260
261       zip ARRAY1 ARRAY2 [ ARRAY3 ... ]
262
263       Returns a list consisting of the first elements of each array, then the
264       second, then the third, etc, until all arrays are exhausted.
265
266       Examples:
267
268         @x = qw/a b c d/;
269         @y = qw/1 2 3 4/;
270         @z = mesh @x, @y;         # returns a, 1, b, 2, c, 3, d, 4
271
272         @a = ('x');
273         @b = ('1', '2');
274         @c = qw/zip zap zot/;
275         @d = mesh @a, @b, @c;   # x, 1, zip, undef, 2, zap, undef, undef, zot
276
277       "zip" is an alias for "mesh".
278
279       zip6
280
281       zip_unflatten
282
283       Returns a list of arrays consisting of the first elements of each
284       array, then the second, then the third, etc, until all arrays are
285       exhausted.
286
287         @x = qw/a b c d/;
288         @y = qw/1 2 3 4/;
289         @z = zip6 @x, @y;         # returns [a, 1], [b, 2], [c, 3], [d, 4]
290
291         @a = ('x');
292         @b = ('1', '2');
293         @c = qw/zip zap zot/;
294         @d = zip6 @a, @b, @c;     # [x, 1, zip], [undef, 2, zap], [undef, undef, zot]
295
296       "zip_unflatten" is an alias for "zip6".
297
298       listcmp ARRAY0 ARRAY1 [ ARRAY2 ... ]
299
300       Returns an associative list of elements and every id of the list it was
301       found in. Allowes easy implementation of @a & @b, @a | @b, @a ^ @b and
302       so on.  Undefined entries in any given array are skipped.
303
304         my @a = qw(one two three four five six seven eight nine ten eleven twelve thirteen);
305         my @b = qw(two three five seven eleven thirteen seventeen);
306         my @c = qw(one one two three five eight thirteen twentyone);
307         my %cmp = listcmp @a, @b, @c; # returns (one => [0, 2], two => [0, 1, 2], three => [0, 1, 2], four => [0], ...)
308
309         my @seq = (1, 2, 3);
310         my @prim = (undef, 2, 3, 5);
311         my @fib = (1, 1, 2);
312         my $cmp = listcmp @seq, @prim, @fib;
313         # returns { 1 => [0, 2], 2 => [0, 1, 2], 3 => [0, 1], 5 => [1] }
314
315       arrayify LIST[,LIST[,LIST...]]
316
317       Returns a list costisting of each element of given arrays. Recursive
318       arrays are flattened, too.
319
320         @a = (1, [[2], 3], 4, [5], 6, [7], 8, 9);
321         @l = arrayify @a;         # returns 1, 2, 3, 4, 5, 6, 7, 8, 9
322
323       uniq LIST
324
325       distinct LIST
326
327       Returns a new list by stripping duplicate values in LIST by comparing
328       the values as hash keys, except that undef is considered separate from
329       ''.  The order of elements in the returned list is the same as in LIST.
330       In scalar context, returns the number of unique elements in LIST.
331
332         my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 1 2 3 5 4
333         my $x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 5
334         # returns "Mike", "Michael", "Richard", "Rick"
335         my @n = distinct "Mike", "Michael", "Richard", "Rick", "Michael", "Rick"
336         # returns "A8", "", undef, "A5", "S1"
337         my @s = distinct "A8", "", undef, "A5", "S1", "A5", "A8"
338         # returns "Giulia", "Giulietta", undef, "", 156, "GTA", "GTV", 159, "Brera", "4C"
339         my @w = uniq "Giulia", "Giulietta", undef, "", 156, "GTA", "GTV", 159, "Brera", "4C", "Giulietta", "Giulia"
340
341       "distinct" is an alias for "uniq".
342
343       RT#49800 can be used to give feedback about this behavior.
344
345       singleton LIST
346
347       Returns a new list by stripping values in LIST occurring more than once
348       by comparing the values as hash keys, except that undef is considered
349       separate from ''.  The order of elements in the returned list is the
350       same as in LIST.  In scalar context, returns the number of elements
351       occurring only once in LIST.
352
353         my @x = singleton 1,1,2,2,3,4,5 # returns 3 4 5
354
355       duplicates LIST
356
357       Returns a new list by stripping values in LIST occuring less than twice
358       by comparing the values as hash keys, except that undef is considered
359       separate from ''.  The order of elements in the returned list is the
360       same as in LIST.  In scalar context, returns the number of elements
361       occurring only once in LIST.
362
363         my @y = duplicates 1,1,2,4,7,2,3,4,6,9; #returns 1,2,4
364
365       frequency LIST
366
367       Returns an associative list of distinct values and the corresponding
368       frequency.
369
370         my @f = frequency values %radio_nrw; # returns (
371         #  'Deutschlandfunk (DLF)' => 9, 'WDR 3' => 10,
372         #  'WDR 4' => 11, 'WDR 5' => 14, 'WDR Eins Live' => 14,
373         #  'Deutschlandradio Kultur' => 8,...)
374
375       occurrences LIST
376
377       Returns a new list of frequencies and the corresponding values from
378       LIST.
379
380         my @o = occurrences ((1) x 3, (2) x 4, (3) x 2, (4) x 7, (5) x 2, (6) x 4);
381         #  @o = (undef, undef, [3, 5], [1], [2, 6], undef, undef, [4]);
382
383       mode LIST
384
385       Returns the modal value of LIST. In scalar context, just the modal
386       value is returned, in list context all probes occuring modal times are
387       returned, too.
388
389         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);
390         #  @m = (7, 4, 8) - bimodal LIST
391
392   Partitioning
393       after BLOCK LIST
394
395       Returns a list of the values of LIST after (and not including) the
396       point where BLOCK returns a true value. Sets $_ for each element in
397       LIST in turn.
398
399         @x = after { $_ % 5 == 0 } (1..9);    # returns 6, 7, 8, 9
400
401       after_incl BLOCK LIST
402
403       Same as "after" but also includes the element for which BLOCK is true.
404
405       before BLOCK LIST
406
407       Returns a list of values of LIST up to (and not including) the point
408       where BLOCK returns a true value. Sets $_ for each element in LIST in
409       turn.
410
411       before_incl BLOCK LIST
412
413       Same as "before" but also includes the element for which BLOCK is true.
414
415       part BLOCK LIST
416
417       Partitions LIST based on the return value of BLOCK which denotes into
418       which partition the current value is put.
419
420       Returns a list of the partitions thusly created. Each partition created
421       is a reference to an array.
422
423         my $i = 0;
424         my @part = part { $i++ % 2 } 1 .. 8;   # returns [1, 3, 5, 7], [2, 4, 6, 8]
425
426       You can have a sparse list of partitions as well where non-set
427       partitions will be undef:
428
429         my @part = part { 2 } 1 .. 10;            # returns undef, undef, [ 1 .. 10 ]
430
431       Be careful with negative values, though:
432
433         my @part = part { -1 } 1 .. 10;
434         __END__
435         Modification of non-creatable array value attempted, subscript -1 ...
436
437       Negative values are only ok when they refer to a partition previously
438       created:
439
440         my @idx  = ( 0, 1, -1 );
441         my $i    = 0;
442         my @part = part { $idx[$++ % 3] } 1 .. 8; # [1, 4, 7], [2, 3, 5, 6, 8]
443
444       samples COUNT LIST
445
446       Returns a new list containing COUNT random samples from LIST. Is
447       similar to "shuffle" in List::Util, but stops after COUNT.
448
449         @r  = samples 10, 1..10; # same as shuffle
450         @r2 = samples 5, 1..10; # gives 5 values from 1..10;
451
452   Iteration
453       each_array ARRAY1 ARRAY2 ...
454
455       Creates an array iterator to return the elements of the list of arrays
456       ARRAY1, ARRAY2 throughout ARRAYn in turn.  That is, the first time it
457       is called, it returns the first element of each array.  The next time,
458       it returns the second elements.  And so on, until all elements are
459       exhausted.
460
461       This is useful for looping over more than one array at once:
462
463         my $ea = each_array(@a, @b, @c);
464         while ( my ($a, $b, $c) = $ea->() )   { .... }
465
466       The iterator returns the empty list when it reached the end of all
467       arrays.
468
469       If the iterator is passed an argument of '"index"', then it returns the
470       index of the last fetched set of values, as a scalar.
471
472       each_arrayref LIST
473
474       Like each_array, but the arguments are references to arrays, not the
475       plain arrays.
476
477       natatime EXPR, LIST
478
479       Creates an array iterator, for looping over an array in chunks of $n
480       items at a time.  (n at a time, get it?).  An example is probably a
481       better explanation than I could give in words.
482
483       Example:
484
485         my @x = ('a' .. 'g');
486         my $it = natatime 3, @x;
487         while (my @vals = $it->())
488         {
489           print "@vals\n";
490         }
491
492       This prints
493
494         a b c
495         d e f
496         g
497
498   Searching
499       firstval BLOCK LIST
500
501       first_value BLOCK LIST
502
503       Returns the first element in LIST for which BLOCK evaluates to true.
504       Each element of LIST is set to $_ in turn. Returns "undef" if no such
505       element has been found.
506
507       "first_value" is an alias for "firstval".
508
509       onlyval BLOCK LIST
510
511       only_value BLOCK LIST
512
513       Returns the only element in LIST for which BLOCK evaluates to true.
514       Sets $_ for each item in LIST in turn. Returns "undef" if no such
515       element has been found.
516
517       "only_value" is an alias for "onlyval".
518
519       lastval BLOCK LIST
520
521       last_value BLOCK LIST
522
523       Returns the last value in LIST for which BLOCK evaluates to true. Each
524       element of LIST is set to $_ in turn. Returns "undef" if no such
525       element has been found.
526
527       "last_value" is an alias for "lastval".
528
529       firstres BLOCK LIST
530
531       first_result BLOCK LIST
532
533       Returns the result of BLOCK for the first element in LIST for which
534       BLOCK evaluates to true. Each element of LIST is set to $_ in turn.
535       Returns "undef" if no such element has been found.
536
537       "first_result" is an alias for "firstres".
538
539       onlyres BLOCK LIST
540
541       only_result BLOCK LIST
542
543       Returns the result of BLOCK for the first element in LIST for which
544       BLOCK evaluates to true. Sets $_ for each item in LIST in turn. Returns
545       "undef" if no such element has been found.
546
547       "only_result" is an alias for "onlyres".
548
549       lastres BLOCK LIST
550
551       last_result BLOCK LIST
552
553       Returns the result of BLOCK for the last element in LIST for which
554       BLOCK evaluates to true. Each element of LIST is set to $_ in turn.
555       Returns "undef" if no such element has been found.
556
557       "last_result" is an alias for "lastres".
558
559       indexes BLOCK LIST
560
561       Evaluates BLOCK for each element in LIST (assigned to $_) and returns a
562       list of the indices of those elements for which BLOCK returned a true
563       value. This is just like "grep" only that it returns indices instead of
564       values:
565
566         @x = indexes { $_ % 2 == 0 } (1..10);   # returns 1, 3, 5, 7, 9
567
568       firstidx BLOCK LIST
569
570       first_index BLOCK LIST
571
572       Returns the index of the first element in LIST for which the criterion
573       in BLOCK is true. Sets $_ for each item in LIST in turn:
574
575         my @list = (1, 4, 3, 2, 4, 6);
576         printf "item with index %i in list is 4", firstidx { $_ == 4 } @list;
577         __END__
578         item with index 1 in list is 4
579
580       Returns "-1" if no such item could be found.
581
582       "first_index" is an alias for "firstidx".
583
584       onlyidx BLOCK LIST
585
586       only_index BLOCK LIST
587
588       Returns the index of the only element in LIST for which the criterion
589       in BLOCK is true. Sets $_ for each item in LIST in turn:
590
591           my @list = (1, 3, 4, 3, 2, 4);
592           printf "uniqe index of item 2 in list is %i", onlyidx { $_ == 2 } @list;
593           __END__
594           unique index of item 2 in list is 4
595
596       Returns "-1" if either no such item or more than one of these has been
597       found.
598
599       "only_index" is an alias for "onlyidx".
600
601       lastidx BLOCK LIST
602
603       last_index BLOCK LIST
604
605       Returns the index of the last element in LIST for which the criterion
606       in BLOCK is true. Sets $_ for each item in LIST in turn:
607
608         my @list = (1, 4, 3, 2, 4, 6);
609         printf "item with index %i in list is 4", lastidx { $_ == 4 } @list;
610         __END__
611         item with index 4 in list is 4
612
613       Returns "-1" if no such item could be found.
614
615       "last_index" is an alias for "lastidx".
616
617   Sorting
618       sort_by BLOCK LIST
619
620       Returns the list of values sorted according to the string values
621       returned by the KEYFUNC block or function. A typical use of this may be
622       to sort objects according to the string value of some accessor, such as
623
624         sort_by { $_->name } @people
625
626       The key function is called in scalar context, being passed each value
627       in turn as both $_ and the only argument in the parameters, @_. The
628       values are then sorted according to string comparisons on the values
629       returned.  This is equivalent to
630
631         sort { $a->name cmp $b->name } @people
632
633       except that it guarantees the name accessor will be executed only once
634       per value.  One interesting use-case is to sort strings which may have
635       numbers embedded in them "naturally", rather than lexically.
636
637         sort_by { s/(\d+)/sprintf "%09d", $1/eg; $_ } @strings
638
639       This sorts strings by generating sort keys which zero-pad the embedded
640       numbers to some level (9 digits in this case), helping to ensure the
641       lexical sort puts them in the correct order.
642
643       nsort_by BLOCK LIST
644
645       Similar to sort_by but compares its key values numerically.
646
647       qsort BLOCK ARRAY
648
649       This sorts the given array in place using the given compare code.
650       Except for tiny compare code like "$a <=> $b", qsort is much faster
651       than Perl's "sort" depending on the version.
652
653       Compared 5.8 and 5.26:
654
655         my @rl;
656         for(my $i = 0; $i < 1E6; ++$i) { push @rl, rand(1E5) }
657         my $idx;
658
659         sub ext_cmp { $_[0] <=> $_[1] }
660
661         cmpthese( -60, {
662             'qsort' => sub {
663                 my @qrl = @rl;
664                 qsort { ext_cmp($a, $b) } @qrl;
665                 $idx = bsearchidx { ext_cmp($_, $rl[0]) } @qrl
666             },
667             'reverse qsort' => sub {
668                 my @qrl = @rl;
669                 qsort { ext_cmp($b, $a) } @qrl;
670                 $idx = bsearchidx { ext_cmp($rl[0], $_) } @qrl
671             },
672             'sort' => sub {
673                 my @srl = @rl;
674                 @srl = sort { ext_cmp($a, $b) } @srl;
675                 $idx = bsearchidx { ext_cmp($_, $rl[0]) } @srl
676             },
677             'reverse sort' => sub {
678                 my @srl = @rl;
679                 @srl = sort { ext_cmp($b, $a) } @srl;
680                 $idx = bsearchidx { ext_cmp($rl[0], $_) } @srl
681             },
682         });
683
684       5.8 results
685
686                         s/iter  reverse sort          sort reverse qsort         qsort
687         reverse sort    6.21            --           -0%           -8%          -10%
688         sort            6.19            0%            --           -7%          -10%
689         reverse qsort   5.73            8%            8%            --           -2%
690         qsort           5.60           11%           11%            2%            --
691
692       5.26 results
693
694                       s/iter  reverse sort          sort reverse qsort         qsort
695         reverse sort    4.54            --           -0%          -96%          -96%
696         sort            4.52            0%            --          -96%          -96%
697         reverse qsort  0.203         2139%         2131%            --          -19%
698         qsort          0.164         2666%         2656%           24%            --
699
700       Use it where external data sources might have to be compared (think of
701       Unix::Statgrab "tables").
702
703       "qsort" is available from List::MoreUtils::XS only. It's insane to
704       maintain a wrapper around Perl's sort nor having a pure Perl
705       implementation. One could create a flip-book in same speed as PP runs a
706       qsort.
707
708   Searching in sorted Lists
709       bsearch BLOCK LIST
710
711       Performs a binary search on LIST which must be a sorted list of values.
712       BLOCK must return a negative value if the current element (stored in
713       $_) is smaller, a positive value if it is bigger and zero if it
714       matches.
715
716       Returns a boolean value in scalar context. In list context, it returns
717       the element if it was found, otherwise the empty list.
718
719       bsearchidx BLOCK LIST
720
721       bsearch_index BLOCK LIST
722
723       Performs a binary search on LIST which must be a sorted list of values.
724       BLOCK must return a negative value if the current element (stored in
725       $_) is smaller, a positive value if it is bigger and zero if it
726       matches.
727
728       Returns the index of found element, otherwise "-1".
729
730       "bsearch_index" is an alias for "bsearchidx".
731
732       lower_bound BLOCK LIST
733
734       Returns the index of the first element in LIST which does not compare
735       less than val. Technically it's the first element in LIST which does
736       not return a value below zero when passed to BLOCK.
737
738         @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);
739         $lb = lower_bound { $_ <=> 2 } @ids; # returns 2
740         $lb = lower_bound { $_ <=> 4 } @ids; # returns 10
741
742       lower_bound has a complexity of O(log n).
743
744       upper_bound BLOCK LIST
745
746       Returns the index of the first element in LIST which does not compare
747       greater than val. Technically it's the first element in LIST which does
748       not return a value below or equal to zero when passed to BLOCK.
749
750         @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);
751         $lb = upper_bound { $_ <=> 2 } @ids; # returns 4
752         $lb = upper_bound { $_ <=> 4 } @ids; # returns 14
753
754       upper_bound has a complexity of O(log n).
755
756       equal_range BLOCK LIST
757
758       Returns a pair of indices containing the lower_bound and the
759       upper_bound.
760
761   Operations on sorted Lists
762       binsert BLOCK ITEM LIST
763
764       bsearch_insert BLOCK ITEM LIST
765
766       Performs a binary search on LIST which must be a sorted list of values.
767       BLOCK must return a negative value if the current element (stored in
768       $_) is smaller, a positive value if it is bigger and zero if it
769       matches.
770
771       ITEM is inserted at the index where the ITEM should be placed (based on
772       above search). That means, it's inserted before the next bigger
773       element.
774
775         @l = (2,3,5,7);
776         binsert { $_ <=> 4 }  4, @l; # @l = (2,3,4,5,7)
777         binsert { $_ <=> 6 } 42, @l; # @l = (2,3,4,42,7)
778
779       You take care that the inserted element matches the compare result.
780
781       bremove BLOCK LIST
782
783       bsearch_remove BLOCK LIST
784
785       Performs a binary search on LIST which must be a sorted list of values.
786       BLOCK must return a negative value if the current element (stored in
787       $_) is smaller, a positive value if it is bigger and zero if it
788       matches.
789
790       The item at the found position is removed and returned.
791
792         @l = (2,3,4,5,7);
793         bremove { $_ <=> 4 }, @l; # @l = (2,3,5,7);
794
795   Counting and calculation
796       true BLOCK LIST
797
798       Counts the number of elements in LIST for which the criterion in BLOCK
799       is true.  Sets $_ for  each item in LIST in turn:
800
801         printf "%i item(s) are defined", true { defined($_) } @list;
802
803       false BLOCK LIST
804
805       Counts the number of elements in LIST for which the criterion in BLOCK
806       is false.  Sets $_ for each item in LIST in turn:
807
808         printf "%i item(s) are not defined", false { defined($_) } @list;
809
810       reduce_0 BLOCK LIST
811
812       Reduce LIST by calling BLOCK in scalar context for each element of
813       LIST.  $a contains the progressional result and is initialized with 0.
814       $b contains the current processed element of LIST and $_ contains the
815       index of the element in $b.
816
817       The idea behind reduce_0 is summation (addition of a sequence of
818       numbers).
819
820       reduce_1 BLOCK LIST
821
822       Reduce LIST by calling BLOCK in scalar context for each element of
823       LIST.  $a contains the progressional result and is initialized with 1.
824       $b contains the current processed element of LIST and $_ contains the
825       index of the element in $b.
826
827       The idea behind reduce_1 is product of a sequence of numbers.
828
829       reduce_u BLOCK LIST
830
831       Reduce LIST by calling BLOCK in scalar context for each element of
832       LIST.  $a contains the progressional result and is initialized with 1.
833       $b contains the current processed element of LIST and $_ contains the
834       index of the element in $b.
835
836       This function has been added if one might need the extra of the index
837       value but need an individual initialization.
838
839       Use with caution: In most cases "reduce" in List::Util will do the job
840       better.
841
842       minmax LIST
843
844       Calculates the minimum and maximum of LIST and returns a two element
845       list with the first element being the minimum and the second the
846       maximum. Returns the empty list if LIST was empty.
847
848       The "minmax" algorithm differs from a naive iteration over the list
849       where each element is compared to two values being the so far
850       calculated min and max value in that it only requires 3n/2 - 2
851       comparisons. Thus it is the most efficient possible algorithm.
852
853       However, the Perl implementation of it has some overhead simply due to
854       the fact that there are more lines of Perl code involved. Therefore,
855       LIST needs to be fairly big in order for "minmax" to win over a naive
856       implementation. This limitation does not apply to the XS version.
857
858       minmaxstr LIST
859
860       Computes the minimum and maximum of LIST using string compare and
861       returns a two element list with the first element being the minimum and
862       the second the maximum. Returns the empty list if LIST was empty.
863
864       The implementation is similar to "minmax".
865

ENVIRONMENT

867       When "LIST_MOREUTILS_PP" is set, the module will always use the pure-
868       Perl implementation and not the XS one. This environment variable is
869       really just there for the test-suite to force testing the Perl
870       implementation, and possibly for reporting of bugs. I don't see any
871       reason to use it in a production environment.
872

MAINTENANCE

874       The maintenance goal is to preserve the documented semantics of the
875       API; bug fixes that bring actual behavior in line with semantics are
876       allowed.  New API functions may be added over time.  If a backwards
877       incompatible change is unavoidable, we will attempt to provide support
878       for the legacy API using the same export tag mechanism currently in
879       place.
880
881       This module attempts to use few non-core dependencies. Non-core
882       configuration and testing modules will be bundled when reasonable; run-
883       time dependencies will be added only if they deliver substantial
884       benefit.
885

CONTRIBUTING

887       While contributions are appreciated, a contribution should not cause
888       more effort for the maintainer than the contribution itself saves (see
889       Open Source Contribution Etiquette
890       <http://tirania.org/blog/archive/2010/Dec-31.html>).
891
892       To get more familiar where help could be needed - see
893       List::MoreUtils::Contributing.
894

BUGS

896       There is a problem with a bug in 5.6.x perls. It is a syntax error to
897       write things like:
898
899           my @x = apply { s/foo/bar/ } qw{ foo bar baz };
900
901       It has to be written as either
902
903           my @x = apply { s/foo/bar/ } 'foo', 'bar', 'baz';
904
905       or
906
907           my @x = apply { s/foo/bar/ } my @dummy = qw/foo bar baz/;
908
909       Perl 5.5.x and Perl 5.8.x don't suffer from this limitation.
910
911       If you have a functionality that you could imagine being in this
912       module, please drop me a line. This module's policy will be less strict
913       than List::Util's when it comes to additions as it isn't a core module.
914
915       When you report bugs, it would be nice if you could additionally give
916       me the output of your program with the environment variable
917       "LIST_MOREUTILS_PP" set to a true value. That way I know where to look
918       for the problem (in XS, pure-Perl or possibly both).
919

SUPPORT

921       Bugs should always be submitted via the CPAN bug tracker.
922
923       You can find documentation for this module with the perldoc command.
924
925           perldoc List::MoreUtils
926
927       You can also look for information at:
928
929       ·   RT: CPAN's request tracker
930
931           <https://rt.cpan.org/Dist/Display.html?Name=List-MoreUtils>
932
933       ·   AnnoCPAN: Annotated CPAN documentation
934
935           <http://annocpan.org/dist/List-MoreUtils>
936
937       ·   CPAN Ratings
938
939           <http://cpanratings.perl.org/dist/List-MoreUtils>
940
941       ·   MetaCPAN
942
943           <https://metacpan.org/release/List-MoreUtils>
944
945       ·   CPAN Search
946
947           <http://search.cpan.org/dist/List-MoreUtils/>
948
949       ·   Git Repository
950
951           <https://github.com/perl5-utils/List-MoreUtils>
952
953   Where can I go for help?
954       If you have a bug report, a patch or a suggestion, please open a new
955       report ticket at CPAN (but please check previous reports first in case
956       your issue has already been addressed) or open an issue on GitHub.
957
958       Report tickets should contain a detailed description of the bug or
959       enhancement request and at least an easily verifiable way of
960       reproducing the issue or fix. Patches are always welcome, too - and
961       it's cheap to send pull-requests on GitHub. Please keep in mind that
962       code changes are more likely accepted when they're bundled with an
963       approving test.
964
965       If you think you've found a bug then please read "How to Report Bugs
966       Effectively" by Simon Tatham:
967       <http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>.
968
969   Where can I go for help with a concrete version?
970       Bugs and feature requests are accepted against the latest version only.
971       To get patches for earlier versions, you need to get an agreement with
972       a developer of your choice - who may or not report the issue and a
973       suggested fix upstream (depends on the license you have chosen).
974
975   Business support and maintenance
976       Generally, in volunteered projects, there is no right for support.
977       While every maintainer is happy to improve the provided software, spare
978       time is limited.
979
980       For those who have a use case which requires guaranteed support, one of
981       the maintainers should be hired or contracted.  For business support
982       you can contact Jens via his CPAN email address rehsackATcpan.org.
983       Please keep in mind that business support is neither available for free
984       nor are you eligible to receive any support based on the license
985       distributed with this package.
986

THANKS

988   Tassilo von Parseval
989       Credits go to a number of people: Steve Purkis for giving me namespace
990       advice and James Keenan and Terrence Branno for their effort of keeping
991       the CPAN tidier by making List::Utils obsolete.
992
993       Brian McCauley suggested the inclusion of apply() and provided the
994       pure-Perl implementation for it.
995
996       Eric J. Roode asked me to add all functions from his module
997       "List::MoreUtil" into this one. With minor modifications, the pure-Perl
998       implementations of those are by him.
999
1000       The bunch of people who almost immediately pointed out the many
1001       problems with the glitchy 0.07 release (Slaven Rezic, Ron Savage, CPAN
1002       testers).
1003
1004       A particularly nasty memory leak was spotted by Thomas A. Lowery.
1005
1006       Lars Thegler made me aware of problems with older Perl versions.
1007
1008       Anno Siegel de-orphaned each_arrayref().
1009
1010       David Filmer made me aware of a problem in each_arrayref that could
1011       ultimately lead to a segfault.
1012
1013       Ricardo Signes suggested the inclusion of part() and provided the Perl-
1014       implementation.
1015
1016       Robin Huston kindly fixed a bug in perl's MULTICALL API to make the XS-
1017       implementation of part() work.
1018
1019   Jens Rehsack
1020       Credits goes to all people contributing feedback during the v0.400
1021       development releases.
1022
1023       Special thanks goes to David Golden who spent a lot of effort to
1024       develop a design to support current state of CPAN as well as ancient
1025       software somewhere in the dark. He also contributed a lot of patches to
1026       refactor the API frontend to welcome any user of List::MoreUtils - from
1027       ancient past to recently last used.
1028
1029       Toby Inkster provided a lot of useful feedback for sane importer code
1030       and was a nice sounding board for API discussions.
1031
1032       Peter Rabbitson provided a sane git repository setup containing entire
1033       package history.
1034

TODO

1036       A pile of requests from other people is still pending further
1037       processing in my mailbox. This includes:
1038
1039       ·   delete_index
1040
1041       ·   random_item
1042
1043       ·   random_item_delete_index
1044
1045       ·   list_diff_hash
1046
1047       ·   list_diff_inboth
1048
1049       ·   list_diff_infirst
1050
1051       ·   list_diff_insecond
1052
1053           These were all suggested by Dan Muey.
1054
1055       ·   listify
1056
1057           Always return a flat list when either a simple scalar value was
1058           passed or an array-reference. Suggested by Mark Summersault.
1059

SEE ALSO

1061       List::Util, List::AllUtils, List::UtilsBy
1062

AUTHOR

1064       Jens Rehsack <rehsack AT cpan.org>
1065
1066       Adam Kennedy <adamk@cpan.org>
1067
1068       Tassilo von Parseval <tassilo.von.parseval@rwth-aachen.de>
1069
1071       Some parts copyright 2011 Aaron Crane.
1072
1073       Copyright 2004 - 2010 by Tassilo von Parseval
1074
1075       Copyright 2013 - 2017 by Jens Rehsack
1076
1077       All code added with 0.417 or later is licensed under the Apache
1078       License, Version 2.0 (the "License"); you may not use this file except
1079       in compliance with the License. You may obtain a copy of the License at
1080
1081        http://www.apache.org/licenses/LICENSE-2.0
1082
1083       Unless required by applicable law or agreed to in writing, software
1084       distributed under the License is distributed on an "AS IS" BASIS,
1085       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
1086       implied.  See the License for the specific language governing
1087       permissions and limitations under the License.
1088
1089       All code until 0.416 is licensed under the same terms as Perl itself,
1090       either Perl version 5.8.4 or, at your option, any later version of Perl
1091       5 you may have available.
1092
1093
1094
1095perl v5.30.0                      2019-07-26                List::MoreUtils(3)
Impressum