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

ENVIRONMENT

901       When "LIST_MOREUTILS_PP" is set, the module will always use the pure-
902       Perl implementation and not the XS one. This environment variable is
903       really just there for the test-suite to force testing the Perl
904       implementation, and possibly for reporting of bugs. I don't see any
905       reason to use it in a production environment.
906

MAINTENANCE

908       The maintenance goal is to preserve the documented semantics of the
909       API; bug fixes that bring actual behavior in line with semantics are
910       allowed.  New API functions may be added over time.  If a backwards
911       incompatible change is unavoidable, we will attempt to provide support
912       for the legacy API using the same export tag mechanism currently in
913       place.
914
915       This module attempts to use few non-core dependencies. Non-core
916       configuration and testing modules will be bundled when reasonable; run-
917       time dependencies will be added only if they deliver substantial
918       benefit.
919

CONTRIBUTING

921       While contributions are appreciated, a contribution should not cause
922       more effort for the maintainer than the contribution itself saves (see
923       Open Source Contribution Etiquette
924       <http://tirania.org/blog/archive/2010/Dec-31.html>).
925
926       To get more familiar where help could be needed - see
927       List::MoreUtils::Contributing.
928

BUGS

930       There is a problem with a bug in 5.6.x perls. It is a syntax error to
931       write things like:
932
933           my @x = apply { s/foo/bar/ } qw{ foo bar baz };
934
935       It has to be written as either
936
937           my @x = apply { s/foo/bar/ } 'foo', 'bar', 'baz';
938
939       or
940
941           my @x = apply { s/foo/bar/ } my @dummy = qw/foo bar baz/;
942
943       Perl 5.5.x and Perl 5.8.x don't suffer from this limitation.
944
945       If you have a functionality that you could imagine being in this
946       module, please drop me a line. This module's policy will be less strict
947       than List::Util's when it comes to additions as it isn't a core module.
948
949       When you report bugs, it would be nice if you could additionally give
950       me the output of your program with the environment variable
951       "LIST_MOREUTILS_PP" set to a true value. That way I know where to look
952       for the problem (in XS, pure-Perl or possibly both).
953

SUPPORT

955       Bugs should always be submitted via the CPAN bug tracker.
956
957       You can find documentation for this module with the perldoc command.
958
959           perldoc List::MoreUtils
960
961       You can also look for information at:
962
963       •   RT: CPAN's request tracker
964
965           <https://rt.cpan.org/Dist/Display.html?Name=List-MoreUtils>
966
967       •   AnnoCPAN: Annotated CPAN documentation
968
969           <http://annocpan.org/dist/List-MoreUtils>
970
971       •   CPAN Ratings
972
973           <http://cpanratings.perl.org/dist/List-MoreUtils>
974
975       •   MetaCPAN
976
977           <https://metacpan.org/release/List-MoreUtils>
978
979       •   CPAN Search
980
981           <http://search.cpan.org/dist/List-MoreUtils/>
982
983       •   Git Repository
984
985           <https://github.com/perl5-utils/List-MoreUtils>
986
987   Where can I go for help?
988       If you have a bug report, a patch or a suggestion, please open a new
989       report ticket at CPAN (but please check previous reports first in case
990       your issue has already been addressed) or open an issue on GitHub.
991
992       Report tickets should contain a detailed description of the bug or
993       enhancement request and at least an easily verifiable way of
994       reproducing the issue or fix. Patches are always welcome, too - and
995       it's cheap to send pull-requests on GitHub. Please keep in mind that
996       code changes are more likely accepted when they're bundled with an
997       approving test.
998
999       If you think you've found a bug then please read "How to Report Bugs
1000       Effectively" by Simon Tatham:
1001       <http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>.
1002
1003   Where can I go for help with a concrete version?
1004       Bugs and feature requests are accepted against the latest version only.
1005       To get patches for earlier versions, you need to get an agreement with
1006       a developer of your choice - who may or not report the issue and a
1007       suggested fix upstream (depends on the license you have chosen).
1008
1009   Business support and maintenance
1010       Generally, in volunteered projects, there is no right for support.
1011       While every maintainer is happy to improve the provided software, spare
1012       time is limited.
1013
1014       For those who have a use case which requires guaranteed support, one of
1015       the maintainers should be hired or contracted.  For business support
1016       you can contact Jens via his CPAN email address rehsackATcpan.org.
1017       Please keep in mind that business support is neither available for free
1018       nor are you eligible to receive any support based on the license
1019       distributed with this package.
1020

THANKS

1022   Tassilo von Parseval
1023       Credits go to a number of people: Steve Purkis for giving me namespace
1024       advice and James Keenan and Terrence Branno for their effort of keeping
1025       the CPAN tidier by making List::Utils obsolete.
1026
1027       Brian McCauley suggested the inclusion of apply() and provided the
1028       pure-Perl implementation for it.
1029
1030       Eric J. Roode asked me to add all functions from his module
1031       "List::MoreUtil" into this one. With minor modifications, the pure-Perl
1032       implementations of those are by him.
1033
1034       The bunch of people who almost immediately pointed out the many
1035       problems with the glitchy 0.07 release (Slaven Rezic, Ron Savage, CPAN
1036       testers).
1037
1038       A particularly nasty memory leak was spotted by Thomas A. Lowery.
1039
1040       Lars Thegler made me aware of problems with older Perl versions.
1041
1042       Anno Siegel de-orphaned each_arrayref().
1043
1044       David Filmer made me aware of a problem in each_arrayref that could
1045       ultimately lead to a segfault.
1046
1047       Ricardo Signes suggested the inclusion of part() and provided the Perl-
1048       implementation.
1049
1050       Robin Huston kindly fixed a bug in perl's MULTICALL API to make the XS-
1051       implementation of part() work.
1052
1053   Jens Rehsack
1054       Credits goes to all people contributing feedback during the v0.400
1055       development releases.
1056
1057       Special thanks goes to David Golden who spent a lot of effort to
1058       develop a design to support current state of CPAN as well as ancient
1059       software somewhere in the dark. He also contributed a lot of patches to
1060       refactor the API frontend to welcome any user of List::MoreUtils - from
1061       ancient past to recently last used.
1062
1063       Toby Inkster provided a lot of useful feedback for sane importer code
1064       and was a nice sounding board for API discussions.
1065
1066       Peter Rabbitson provided a sane git repository setup containing entire
1067       package history.
1068

TODO

1070       A pile of requests from other people is still pending further
1071       processing in my mailbox. This includes:
1072
1073       •   delete_index
1074
1075       •   random_item
1076
1077       •   random_item_delete_index
1078
1079       •   list_diff_hash
1080
1081       •   list_diff_inboth
1082
1083       •   list_diff_infirst
1084
1085       •   list_diff_insecond
1086
1087           These were all suggested by Dan Muey.
1088
1089       •   listify
1090
1091           Always return a flat list when either a simple scalar value was
1092           passed or an array-reference. Suggested by Mark Summersault.
1093

SEE ALSO

1095       List::Util, List::AllUtils, List::UtilsBy
1096

AUTHOR

1098       Jens Rehsack <rehsack AT cpan.org>
1099
1100       Adam Kennedy <adamk@cpan.org>
1101
1102       Tassilo von Parseval <tassilo.von.parseval@rwth-aachen.de>
1103
1105       Some parts copyright 2011 Aaron Crane.
1106
1107       Copyright 2004 - 2010 by Tassilo von Parseval
1108
1109       Copyright 2013 - 2017 by Jens Rehsack
1110
1111       All code added with 0.417 or later is licensed under the Apache
1112       License, Version 2.0 (the "License"); you may not use this file except
1113       in compliance with the License. You may obtain a copy of the License at
1114
1115        http://www.apache.org/licenses/LICENSE-2.0
1116
1117       Unless required by applicable law or agreed to in writing, software
1118       distributed under the License is distributed on an "AS IS" BASIS,
1119       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
1120       implied.  See the License for the specific language governing
1121       permissions and limitations under the License.
1122
1123       All code until 0.416 is licensed under the same terms as Perl itself,
1124       either Perl version 5.8.4 or, at your option, any later version of Perl
1125       5 you may have available.
1126
1127
1128
1129perl v5.36.0                      2023-01-20                List::MoreUtils(3)
Impressum