1List::MoreUtils(3) User Contributed Perl Documentation List::MoreUtils(3)
2
3
4
6 List::MoreUtils - Provide the stuff missing in List::Util
7
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
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
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
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. Allows 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 consisting 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 occurring less than
358 twice by comparing the values as hash keys, except that undef is
359 considered separate from ''. The order of elements in the returned
360 list is the same as in LIST. In scalar context, returns the number of
361 elements occurring more than 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 occurring 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 slide BLOCK LIST
393
394 The function "slide" operates on pairs of list elements like:
395
396 my @s = slide { "$a and $b" } (0..3);
397 # @s = ("0 and 1", "1 and 2", "2 and 3")
398
399 The idea behind this function is a kind of magnifying glass that is
400 moved along a list and calls "BLOCK" every time the next list item is
401 reached.
402
403 Partitioning
404 after BLOCK LIST
405
406 Returns a list of the values of LIST after (and not including) the
407 point where BLOCK returns a true value. Sets $_ for each element in
408 LIST in turn.
409
410 @x = after { $_ % 5 == 0 } (1..9); # returns 6, 7, 8, 9
411
412 after_incl BLOCK LIST
413
414 Same as "after" but also includes the element for which BLOCK is true.
415
416 before BLOCK LIST
417
418 Returns a list of values of LIST up to (and not including) the point
419 where BLOCK returns a true value. Sets $_ for each element in LIST in
420 turn.
421
422 before_incl BLOCK LIST
423
424 Same as "before" but also includes the element for which BLOCK is true.
425
426 part BLOCK LIST
427
428 Partitions LIST based on the return value of BLOCK which denotes into
429 which partition the current value is put.
430
431 Returns a list of the partitions thusly created. Each partition created
432 is a reference to an array.
433
434 my $i = 0;
435 my @part = part { $i++ % 2 } 1 .. 8; # returns [1, 3, 5, 7], [2, 4, 6, 8]
436
437 You can have a sparse list of partitions as well where non-set
438 partitions will be undef:
439
440 my @part = part { 2 } 1 .. 10; # returns undef, undef, [ 1 .. 10 ]
441
442 Be careful with negative values, though:
443
444 my @part = part { -1 } 1 .. 10;
445 __END__
446 Modification of non-creatable array value attempted, subscript -1 ...
447
448 Negative values are only ok when they refer to a partition previously
449 created:
450
451 my @idx = ( 0, 1, -1 );
452 my $i = 0;
453 my @part = part { $idx[$i++ % 3] } 1 .. 8; # [1, 4, 7], [2, 3, 5, 6, 8]
454
455 samples COUNT LIST
456
457 Returns a new list containing COUNT random samples from LIST. Is
458 similar to "shuffle" in List::Util, but stops after COUNT.
459
460 @r = samples 10, 1..10; # same as shuffle
461 @r2 = samples 5, 1..10; # gives 5 values from 1..10;
462
463 Iteration
464 each_array ARRAY1 ARRAY2 ...
465
466 Creates an array iterator to return the elements of the list of arrays
467 ARRAY1, ARRAY2 throughout ARRAYn in turn. That is, the first time it
468 is called, it returns the first element of each array. The next time,
469 it returns the second elements. And so on, until all elements are
470 exhausted.
471
472 This is useful for looping over more than one array at once:
473
474 my $ea = each_array(@a, @b, @c);
475 while ( my ($a, $b, $c) = $ea->() ) { .... }
476
477 The iterator returns the empty list when it reached the end of all
478 arrays.
479
480 If the iterator is passed an argument of '"index"', then it returns the
481 index of the last fetched set of values, as a scalar.
482
483 each_arrayref LIST
484
485 Like each_array, but the arguments are references to arrays, not the
486 plain arrays.
487
488 natatime EXPR, LIST
489
490 Creates an array iterator, for looping over an array in chunks of $n
491 items at a time. (n at a time, get it?). An example is probably a
492 better explanation than I could give in words.
493
494 Example:
495
496 my @x = ('a' .. 'g');
497 my $it = natatime 3, @x;
498 while (my @vals = $it->())
499 {
500 print "@vals\n";
501 }
502
503 This prints
504
505 a b c
506 d e f
507 g
508
509 slideatatime STEP, WINDOW, LIST
510
511 Creates an array iterator, for looping over an array in chunks of
512 "$windows-size" items at a time.
513
514 The idea behind this function is a kind of magnifying glass (finer
515 controllable compared to "slide") that is moved along a list.
516
517 Example:
518
519 my @x = ('a' .. 'g');
520 my $it = slideatatime 2, 3, @x;
521 while (my @vals = $it->())
522 {
523 print "@vals\n";
524 }
525
526 This prints
527
528 a b c
529 c d e
530 e f g
531 g
532
533 Searching
534 firstval BLOCK LIST
535
536 first_value BLOCK LIST
537
538 Returns the first element in LIST for which BLOCK evaluates to true.
539 Each element of LIST is set to $_ in turn. Returns "undef" if no such
540 element has been found.
541
542 "first_value" is an alias for "firstval".
543
544 onlyval BLOCK LIST
545
546 only_value BLOCK LIST
547
548 Returns the only element in LIST for which BLOCK evaluates to true.
549 Sets $_ for each item in LIST in turn. Returns "undef" if no such
550 element has been found.
551
552 "only_value" is an alias for "onlyval".
553
554 lastval BLOCK LIST
555
556 last_value BLOCK LIST
557
558 Returns the last value in LIST for which BLOCK evaluates to true. Each
559 element of LIST is set to $_ in turn. Returns "undef" if no such
560 element has been found.
561
562 "last_value" is an alias for "lastval".
563
564 firstres BLOCK LIST
565
566 first_result BLOCK LIST
567
568 Returns the result of BLOCK for the first element in LIST for which
569 BLOCK evaluates to true. Each element of LIST is set to $_ in turn.
570 Returns "undef" if no such element has been found.
571
572 "first_result" is an alias for "firstres".
573
574 onlyres BLOCK LIST
575
576 only_result BLOCK LIST
577
578 Returns the result of BLOCK for the first element in LIST for which
579 BLOCK evaluates to true. Sets $_ for each item in LIST in turn. Returns
580 "undef" if no such element has been found.
581
582 "only_result" is an alias for "onlyres".
583
584 lastres BLOCK LIST
585
586 last_result BLOCK LIST
587
588 Returns the result of BLOCK for the last element in LIST for which
589 BLOCK evaluates to true. Each element of LIST is set to $_ in turn.
590 Returns "undef" if no such element has been found.
591
592 "last_result" is an alias for "lastres".
593
594 indexes BLOCK LIST
595
596 Evaluates BLOCK for each element in LIST (assigned to $_) and returns a
597 list of the indices of those elements for which BLOCK returned a true
598 value. This is just like "grep" only that it returns indices instead of
599 values:
600
601 @x = indexes { $_ % 2 == 0 } (1..10); # returns 1, 3, 5, 7, 9
602
603 firstidx BLOCK LIST
604
605 first_index BLOCK LIST
606
607 Returns the index of the first element in LIST for which the criterion
608 in BLOCK is true. Sets $_ for each item in LIST in turn:
609
610 my @list = (1, 4, 3, 2, 4, 6);
611 printf "item with index %i in list is 4", firstidx { $_ == 4 } @list;
612 __END__
613 item with index 1 in list is 4
614
615 Returns "-1" if no such item could be found.
616
617 "first_index" is an alias for "firstidx".
618
619 onlyidx BLOCK LIST
620
621 only_index BLOCK LIST
622
623 Returns the index of the only element in LIST for which the criterion
624 in BLOCK is true. Sets $_ for each item in LIST in turn:
625
626 my @list = (1, 3, 4, 3, 2, 4);
627 printf "uniqe index of item 2 in list is %i", onlyidx { $_ == 2 } @list;
628 __END__
629 unique index of item 2 in list is 4
630
631 Returns "-1" if either no such item or more than one of these has been
632 found.
633
634 "only_index" is an alias for "onlyidx".
635
636 lastidx BLOCK LIST
637
638 last_index BLOCK LIST
639
640 Returns the index of the last element in LIST for which the criterion
641 in BLOCK is true. Sets $_ for each item in LIST in turn:
642
643 my @list = (1, 4, 3, 2, 4, 6);
644 printf "item with index %i in list is 4", lastidx { $_ == 4 } @list;
645 __END__
646 item with index 4 in list is 4
647
648 Returns "-1" if no such item could be found.
649
650 "last_index" is an alias for "lastidx".
651
652 Sorting
653 sort_by BLOCK LIST
654
655 Returns the list of values sorted according to the string values
656 returned by the KEYFUNC block or function. A typical use of this may be
657 to sort objects according to the string value of some accessor, such as
658
659 sort_by { $_->name } @people
660
661 The key function is called in scalar context, being passed each value
662 in turn as both $_ and the only argument in the parameters, @_. The
663 values are then sorted according to string comparisons on the values
664 returned. This is equivalent to
665
666 sort { $a->name cmp $b->name } @people
667
668 except that it guarantees the name accessor will be executed only once
669 per value. One interesting use-case is to sort strings which may have
670 numbers embedded in them "naturally", rather than lexically.
671
672 sort_by { s/(\d+)/sprintf "%09d", $1/eg; $_ } @strings
673
674 This sorts strings by generating sort keys which zero-pad the embedded
675 numbers to some level (9 digits in this case), helping to ensure the
676 lexical sort puts them in the correct order.
677
678 nsort_by BLOCK LIST
679
680 Similar to sort_by but compares its key values numerically.
681
682 qsort BLOCK ARRAY
683
684 This sorts the given array in place using the given compare code.
685 Except for tiny compare code like "$a <=> $b", qsort is much faster
686 than Perl's "sort" depending on the version.
687
688 Compared 5.8 and 5.26:
689
690 my @rl;
691 for(my $i = 0; $i < 1E6; ++$i) { push @rl, rand(1E5) }
692 my $idx;
693
694 sub ext_cmp { $_[0] <=> $_[1] }
695
696 cmpthese( -60, {
697 'qsort' => sub {
698 my @qrl = @rl;
699 qsort { ext_cmp($a, $b) } @qrl;
700 $idx = bsearchidx { ext_cmp($_, $rl[0]) } @qrl
701 },
702 'reverse qsort' => sub {
703 my @qrl = @rl;
704 qsort { ext_cmp($b, $a) } @qrl;
705 $idx = bsearchidx { ext_cmp($rl[0], $_) } @qrl
706 },
707 'sort' => sub {
708 my @srl = @rl;
709 @srl = sort { ext_cmp($a, $b) } @srl;
710 $idx = bsearchidx { ext_cmp($_, $rl[0]) } @srl
711 },
712 'reverse sort' => sub {
713 my @srl = @rl;
714 @srl = sort { ext_cmp($b, $a) } @srl;
715 $idx = bsearchidx { ext_cmp($rl[0], $_) } @srl
716 },
717 });
718
719 5.8 results
720
721 s/iter reverse sort sort reverse qsort qsort
722 reverse sort 6.21 -- -0% -8% -10%
723 sort 6.19 0% -- -7% -10%
724 reverse qsort 5.73 8% 8% -- -2%
725 qsort 5.60 11% 11% 2% --
726
727 5.26 results
728
729 s/iter reverse sort sort reverse qsort qsort
730 reverse sort 4.54 -- -0% -96% -96%
731 sort 4.52 0% -- -96% -96%
732 reverse qsort 0.203 2139% 2131% -- -19%
733 qsort 0.164 2666% 2656% 24% --
734
735 Use it where external data sources might have to be compared (think of
736 Unix::Statgrab "tables").
737
738 "qsort" is available from List::MoreUtils::XS only. It's insane to
739 maintain a wrapper around Perl's sort nor having a pure Perl
740 implementation. One could create a flip-book in same speed as PP runs a
741 qsort.
742
743 Searching in sorted Lists
744 bsearch BLOCK LIST
745
746 Performs a binary search on LIST which must be a sorted list of values.
747 BLOCK must return a negative value if the current element (stored in
748 $_) is smaller, a positive value if it is bigger and zero if it
749 matches.
750
751 Returns a boolean value in scalar context. In list context, it returns
752 the element if it was found, otherwise the empty list.
753
754 bsearchidx BLOCK LIST
755
756 bsearch_index BLOCK LIST
757
758 Performs a binary search on LIST which must be a sorted list of values.
759 BLOCK must return a negative value if the current element (stored in
760 $_) is smaller, a positive value if it is bigger and zero if it
761 matches.
762
763 Returns the index of found element, otherwise "-1".
764
765 "bsearch_index" is an alias for "bsearchidx".
766
767 lower_bound BLOCK LIST
768
769 Returns the index of the first element in LIST which does not compare
770 less than val. Technically it's the first element in LIST which does
771 not return a value below zero when passed to BLOCK.
772
773 @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);
774 $lb = lower_bound { $_ <=> 2 } @ids; # returns 2
775 $lb = lower_bound { $_ <=> 4 } @ids; # returns 10
776
777 lower_bound has a complexity of O(log n).
778
779 upper_bound BLOCK LIST
780
781 Returns the index of the first element in LIST which does not compare
782 greater than val. Technically it's the first element in LIST which does
783 not return a value below or equal to zero when passed to BLOCK.
784
785 @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);
786 $lb = upper_bound { $_ <=> 2 } @ids; # returns 4
787 $lb = upper_bound { $_ <=> 4 } @ids; # returns 14
788
789 upper_bound has a complexity of O(log n).
790
791 equal_range BLOCK LIST
792
793 Returns a pair of indices containing the lower_bound and the
794 upper_bound.
795
796 Operations on sorted Lists
797 binsert BLOCK ITEM LIST
798
799 bsearch_insert BLOCK ITEM LIST
800
801 Performs a binary search on LIST which must be a sorted list of values.
802 BLOCK must return a negative value if the current element (stored in
803 $_) is smaller, a positive value if it is bigger and zero if it
804 matches.
805
806 ITEM is inserted at the index where the ITEM should be placed (based on
807 above search). That means, it's inserted before the next bigger
808 element.
809
810 @l = (2,3,5,7);
811 binsert { $_ <=> 4 } 4, @l; # @l = (2,3,4,5,7)
812 binsert { $_ <=> 6 } 42, @l; # @l = (2,3,4,42,7)
813
814 You take care that the inserted element matches the compare result.
815
816 bremove BLOCK LIST
817
818 bsearch_remove BLOCK LIST
819
820 Performs a binary search on LIST which must be a sorted list of values.
821 BLOCK must return a negative value if the current element (stored in
822 $_) is smaller, a positive value if it is bigger and zero if it
823 matches.
824
825 The item at the found position is removed and returned.
826
827 @l = (2,3,4,5,7);
828 bremove { $_ <=> 4 }, @l; # @l = (2,3,5,7);
829
830 Counting and calculation
831 true BLOCK LIST
832
833 Counts the number of elements in LIST for which the criterion in BLOCK
834 is true. Sets $_ for each item in LIST in turn:
835
836 printf "%i item(s) are defined", true { defined($_) } @list;
837
838 false BLOCK LIST
839
840 Counts the number of elements in LIST for which the criterion in BLOCK
841 is false. Sets $_ for each item in LIST in turn:
842
843 printf "%i item(s) are not defined", false { defined($_) } @list;
844
845 reduce_0 BLOCK LIST
846
847 Reduce LIST by calling BLOCK in scalar context for each element of
848 LIST. $a contains the progressional result and is initialized with 0.
849 $b contains the current processed element of LIST and $_ contains the
850 index of the element in $b.
851
852 The idea behind reduce_0 is summation (addition of a sequence of
853 numbers).
854
855 reduce_1 BLOCK LIST
856
857 Reduce LIST by calling BLOCK in scalar context for each element of
858 LIST. $a contains the progressional result and is initialized with 1.
859 $b contains the current processed element of LIST and $_ contains the
860 index of the element in $b.
861
862 The idea behind reduce_1 is product of a sequence of numbers.
863
864 reduce_u BLOCK LIST
865
866 Reduce LIST by calling BLOCK in scalar context for each element of
867 LIST. $a contains the progressional result and is uninitialized. $b
868 contains the current processed element of LIST and $_ contains the
869 index of the element in $b.
870
871 This function has been added if one might need the extra of the index
872 value but need an individual initialization.
873
874 Use with caution: In most cases "reduce" in List::Util will do the job
875 better.
876
877 minmax LIST
878
879 Calculates the minimum and maximum of LIST and returns a two element
880 list with the first element being the minimum and the second the
881 maximum. Returns the empty list if LIST was empty.
882
883 The "minmax" algorithm differs from a naive iteration over the list
884 where each element is compared to two values being the so far
885 calculated min and max value in that it only requires 3n/2 - 2
886 comparisons. Thus it is the most efficient possible algorithm.
887
888 However, the Perl implementation of it has some overhead simply due to
889 the fact that there are more lines of Perl code involved. Therefore,
890 LIST needs to be fairly big in order for "minmax" to win over a naive
891 implementation. This limitation does not apply to the XS version.
892
893 minmaxstr LIST
894
895 Computes the minimum and maximum of LIST using string compare and
896 returns a two element list with the first element being the minimum and
897 the second the maximum. Returns the empty list if LIST was empty.
898
899 The implementation is similar to "minmax".
900
902 When "LIST_MOREUTILS_PP" is set, the module will always use the pure-
903 Perl implementation and not the XS one. This environment variable is
904 really just there for the test-suite to force testing the Perl
905 implementation, and possibly for reporting of bugs. I don't see any
906 reason to use it in a production environment.
907
909 The maintenance goal is to preserve the documented semantics of the
910 API; bug fixes that bring actual behavior in line with semantics are
911 allowed. New API functions may be added over time. If a backwards
912 incompatible change is unavoidable, we will attempt to provide support
913 for the legacy API using the same export tag mechanism currently in
914 place.
915
916 This module attempts to use few non-core dependencies. Non-core
917 configuration and testing modules will be bundled when reasonable; run-
918 time dependencies will be added only if they deliver substantial
919 benefit.
920
922 While contributions are appreciated, a contribution should not cause
923 more effort for the maintainer than the contribution itself saves (see
924 Open Source Contribution Etiquette
925 <http://tirania.org/blog/archive/2010/Dec-31.html>).
926
927 To get more familiar where help could be needed - see
928 List::MoreUtils::Contributing.
929
931 There is a problem with a bug in 5.6.x perls. It is a syntax error to
932 write things like:
933
934 my @x = apply { s/foo/bar/ } qw{ foo bar baz };
935
936 It has to be written as either
937
938 my @x = apply { s/foo/bar/ } 'foo', 'bar', 'baz';
939
940 or
941
942 my @x = apply { s/foo/bar/ } my @dummy = qw/foo bar baz/;
943
944 Perl 5.5.x and Perl 5.8.x don't suffer from this limitation.
945
946 If you have a functionality that you could imagine being in this
947 module, please drop me a line. This module's policy will be less strict
948 than List::Util's when it comes to additions as it isn't a core module.
949
950 When you report bugs, it would be nice if you could additionally give
951 me the output of your program with the environment variable
952 "LIST_MOREUTILS_PP" set to a true value. That way I know where to look
953 for the problem (in XS, pure-Perl or possibly both).
954
956 Bugs should always be submitted via the CPAN bug tracker.
957
958 You can find documentation for this module with the perldoc command.
959
960 perldoc List::MoreUtils
961
962 You can also look for information at:
963
964 • RT: CPAN's request tracker
965
966 <https://rt.cpan.org/Dist/Display.html?Name=List-MoreUtils>
967
968 • AnnoCPAN: Annotated CPAN documentation
969
970 <http://annocpan.org/dist/List-MoreUtils>
971
972 • CPAN Ratings
973
974 <http://cpanratings.perl.org/dist/List-MoreUtils>
975
976 • MetaCPAN
977
978 <https://metacpan.org/release/List-MoreUtils>
979
980 • CPAN Search
981
982 <http://search.cpan.org/dist/List-MoreUtils/>
983
984 • Git Repository
985
986 <https://github.com/perl5-utils/List-MoreUtils>
987
988 Where can I go for help?
989 If you have a bug report, a patch or a suggestion, please open a new
990 report ticket at CPAN (but please check previous reports first in case
991 your issue has already been addressed) or open an issue on GitHub.
992
993 Report tickets should contain a detailed description of the bug or
994 enhancement request and at least an easily verifiable way of
995 reproducing the issue or fix. Patches are always welcome, too - and
996 it's cheap to send pull-requests on GitHub. Please keep in mind that
997 code changes are more likely accepted when they're bundled with an
998 approving test.
999
1000 If you think you've found a bug then please read "How to Report Bugs
1001 Effectively" by Simon Tatham:
1002 <http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>.
1003
1004 Where can I go for help with a concrete version?
1005 Bugs and feature requests are accepted against the latest version only.
1006 To get patches for earlier versions, you need to get an agreement with
1007 a developer of your choice - who may or not report the issue and a
1008 suggested fix upstream (depends on the license you have chosen).
1009
1010 Business support and maintenance
1011 Generally, in volunteered projects, there is no right for support.
1012 While every maintainer is happy to improve the provided software, spare
1013 time is limited.
1014
1015 For those who have a use case which requires guaranteed support, one of
1016 the maintainers should be hired or contracted. For business support
1017 you can contact Jens via his CPAN email address rehsackATcpan.org.
1018 Please keep in mind that business support is neither available for free
1019 nor are you eligible to receive any support based on the license
1020 distributed with this package.
1021
1023 Tassilo von Parseval
1024 Credits go to a number of people: Steve Purkis for giving me namespace
1025 advice and James Keenan and Terrence Branno for their effort of keeping
1026 the CPAN tidier by making List::Utils obsolete.
1027
1028 Brian McCauley suggested the inclusion of apply() and provided the
1029 pure-Perl implementation for it.
1030
1031 Eric J. Roode asked me to add all functions from his module
1032 "List::MoreUtil" into this one. With minor modifications, the pure-Perl
1033 implementations of those are by him.
1034
1035 The bunch of people who almost immediately pointed out the many
1036 problems with the glitchy 0.07 release (Slaven Rezic, Ron Savage, CPAN
1037 testers).
1038
1039 A particularly nasty memory leak was spotted by Thomas A. Lowery.
1040
1041 Lars Thegler made me aware of problems with older Perl versions.
1042
1043 Anno Siegel de-orphaned each_arrayref().
1044
1045 David Filmer made me aware of a problem in each_arrayref that could
1046 ultimately lead to a segfault.
1047
1048 Ricardo Signes suggested the inclusion of part() and provided the Perl-
1049 implementation.
1050
1051 Robin Huston kindly fixed a bug in perl's MULTICALL API to make the XS-
1052 implementation of part() work.
1053
1054 Jens Rehsack
1055 Credits goes to all people contributing feedback during the v0.400
1056 development releases.
1057
1058 Special thanks goes to David Golden who spent a lot of effort to
1059 develop a design to support current state of CPAN as well as ancient
1060 software somewhere in the dark. He also contributed a lot of patches to
1061 refactor the API frontend to welcome any user of List::MoreUtils - from
1062 ancient past to recently last used.
1063
1064 Toby Inkster provided a lot of useful feedback for sane importer code
1065 and was a nice sounding board for API discussions.
1066
1067 Peter Rabbitson provided a sane git repository setup containing entire
1068 package history.
1069
1071 A pile of requests from other people is still pending further
1072 processing in my mailbox. This includes:
1073
1074 • delete_index
1075
1076 • random_item
1077
1078 • random_item_delete_index
1079
1080 • list_diff_hash
1081
1082 • list_diff_inboth
1083
1084 • list_diff_infirst
1085
1086 • list_diff_insecond
1087
1088 These were all suggested by Dan Muey.
1089
1090 • listify
1091
1092 Always return a flat list when either a simple scalar value was
1093 passed or an array-reference. Suggested by Mark Summersault.
1094
1096 List::Util, List::AllUtils, List::UtilsBy
1097
1099 Jens Rehsack <rehsack AT cpan.org>
1100
1101 Adam Kennedy <adamk@cpan.org>
1102
1103 Tassilo von Parseval <tassilo.von.parseval@rwth-aachen.de>
1104
1106 Some parts copyright 2011 Aaron Crane.
1107
1108 Copyright 2004 - 2010 by Tassilo von Parseval
1109
1110 Copyright 2013 - 2017 by Jens Rehsack
1111
1112 All code added with 0.417 or later is licensed under the Apache
1113 License, Version 2.0 (the "License"); you may not use this file except
1114 in compliance with the License. You may obtain a copy of the License at
1115
1116 http://www.apache.org/licenses/LICENSE-2.0
1117
1118 Unless required by applicable law or agreed to in writing, software
1119 distributed under the License is distributed on an "AS IS" BASIS,
1120 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
1121 implied. See the License for the specific language governing
1122 permissions and limitations under the License.
1123
1124 All code until 0.416 is licensed under the same terms as Perl itself,
1125 either Perl version 5.8.4 or, at your option, any later version of Perl
1126 5 you may have available.
1127
1128
1129
1130perl v5.34.0 2021-07-22 List::MoreUtils(3)