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

NAME

6       List::AllUtils - Combines List::Util, List::SomeUtils and List::UtilsBy
7       in one bite-sized package
8

VERSION

10       version 0.15
11

SYNOPSIS

13           use List::AllUtils qw( first any );
14
15           # _Everything_ from List::Util, List::SomeUtils, and List::UtilsBy
16           use List::AllUtils qw( :all );
17
18           my @numbers = ( 1, 2, 3, 5, 7 );
19           # or don't import anything
20           return List::AllUtils::first { $_ > 5 } @numbers;
21

DESCRIPTION

23       Are you sick of trying to remember whether a particular helper is
24       defined in List::Util,  List::SomeUtils or List::UtilsBy? I sure am.
25       Now you don't have to remember. This module will export all of the
26       functions that either of those three modules defines.
27
28       Note that all function documentation has been shamelessly copied from
29       List::Util, List::SomeUtils and List::UtilsBy.
30
31   Which One Wins?
32       Recently, List::Util has started including some of the subs that used
33       to only be in List::SomeUtils. Similar, List::SomeUtils has some small
34       overlap with List::UtilsBy. "List::AllUtils" always favors the version
35       provided by List::Util, List::SomeUtils or List::UtilsBy in that order.
36
37       The docs below come from List::Util 1.31, List::SomeUtils 0.50, and
38       List::UtilsBy 0.10.
39

WHAT IS EXPORTED?

41       All this module does is load List::Util, List::SomeUtils, and
42       List::UtilsBy, and then re-export everything that they provide. That
43       means that regardless of the documentation below, you will get any
44       subroutine that your installed version provides.
45

LIST-REDUCTION FUNCTIONS

47       The following set of functions all reduce a list down to a single
48       value.
49
50   reduce BLOCK LIST
51       Reduces LIST by calling BLOCK, in a scalar context, multiple times,
52       setting $a and $b each time. The first call will be with $a and $b set
53       to the first two elements of the list, subsequent calls will be done by
54       setting $a to the result of the previous call and $b to the next
55       element in the list.
56
57       Returns the result of the last call to BLOCK. If LIST is empty then
58       "undef" is returned. If LIST only contains one element then that
59       element is returned and BLOCK is not executed.
60
61           $foo = reduce { $a < $b ? $a : $b } 1..10       # min
62           $foo = reduce { $a lt $b ? $a : $b } 'aa'..'zz' # minstr
63           $foo = reduce { $a + $b } 1 .. 10               # sum
64           $foo = reduce { $a . $b } @bar                  # concat
65
66       If your algorithm requires that "reduce" produce an identity value,
67       then make sure that you always pass that identity value as the first
68       argument to prevent "undef" being returned
69
70         $foo = reduce { $a + $b } 0, @values;             # sum with 0 identity value
71
72       The remaining list-reduction functions are all specialisations of this
73       generic idea.
74
75   first BLOCK LIST
76       Similar to "grep" in that it evaluates BLOCK setting $_ to each element
77       of LIST in turn. "first" returns the first element where the result
78       from BLOCK is a true value. If BLOCK never returns true or LIST was
79       empty then "undef" is returned.
80
81           $foo = first { defined($_) } @list    # first defined value in @list
82           $foo = first { $_ > $value } @list    # first value in @list which
83                                                 # is greater than $value
84
85       This function could be implemented using "reduce" like this
86
87           $foo = reduce { defined($a) ? $a : wanted($b) ? $b : undef } undef, @list
88
89       for example wanted() could be defined() which would return the first
90       defined value in @list
91
92   max LIST
93       Returns the entry in the list with the highest numerical value. If the
94       list is empty then "undef" is returned.
95
96           $foo = max 1..10                # 10
97           $foo = max 3,9,12               # 12
98           $foo = max @bar, @baz           # whatever
99
100       This function could be implemented using "reduce" like this
101
102           $foo = reduce { $a > $b ? $a : $b } 1..10
103
104   maxstr LIST
105       Similar to "max", but treats all the entries in the list as strings and
106       returns the highest string as defined by the "gt" operator.  If the
107       list is empty then "undef" is returned.
108
109           $foo = maxstr 'A'..'Z'          # 'Z'
110           $foo = maxstr "hello","world"   # "world"
111           $foo = maxstr @bar, @baz        # whatever
112
113       This function could be implemented using "reduce" like this
114
115           $foo = reduce { $a gt $b ? $a : $b } 'A'..'Z'
116
117   min LIST
118       Similar to "max" but returns the entry in the list with the lowest
119       numerical value. If the list is empty then "undef" is returned.
120
121           $foo = min 1..10                # 1
122           $foo = min 3,9,12               # 3
123           $foo = min @bar, @baz           # whatever
124
125       This function could be implemented using "reduce" like this
126
127           $foo = reduce { $a < $b ? $a : $b } 1..10
128
129   minstr LIST
130       Similar to "min", but treats all the entries in the list as strings and
131       returns the lowest string as defined by the "lt" operator.  If the list
132       is empty then "undef" is returned.
133
134           $foo = minstr 'A'..'Z'          # 'A'
135           $foo = minstr "hello","world"   # "hello"
136           $foo = minstr @bar, @baz        # whatever
137
138       This function could be implemented using "reduce" like this
139
140           $foo = reduce { $a lt $b ? $a : $b } 'A'..'Z'
141
142   sum LIST
143       Returns the sum of all the elements in LIST. If LIST is empty then
144       "undef" is returned.
145
146           $foo = sum 1..10                # 55
147           $foo = sum 3,9,12               # 24
148           $foo = sum @bar, @baz           # whatever
149
150       This function could be implemented using "reduce" like this
151
152           $foo = reduce { $a + $b } 1..10
153
154   sum0 LIST
155       Similar to "sum", except this returns 0 when given an empty list,
156       rather than "undef".
157

KEY/VALUE PAIR LIST FUNCTIONS

159       The following set of functions, all inspired by List::Pairwise, consume
160       an even-sized list of pairs. The pairs may be key/value associations
161       from a hash, or just a list of values. The functions will all preserve
162       the original ordering of the pairs, and will not be confused by
163       multiple pairs having the same "key" value - nor even do they require
164       that the first of each pair be a plain string.
165
166   pairgrep BLOCK KVLIST
167       Similar to perl's "grep" keyword, but interprets the given list as an
168       even-sized list of pairs. It invokes the BLOCK multiple times, in
169       scalar context, with $a and $b set to successive pairs of values from
170       the KVLIST.
171
172       Returns an even-sized list of those pairs for which the BLOCK returned
173       true in list context, or the count of the number of pairs in scalar
174       context.  (Note, therefore, in scalar context that it returns a number
175       half the size of the count of items it would have returned in list
176       context).
177
178           @subset = pairgrep { $a =~ m/^[[:upper:]]+$/ } @kvlist
179
180       Similar to "grep", "pairgrep" aliases $a and $b to elements of the
181       given list. Any modifications of it by the code block will be visible
182       to the caller.
183
184   pairfirst BLOCK KVLIST
185       Similar to the "first" function, but interprets the given list as an
186       even-sized list of pairs. It invokes the BLOCK multiple times, in
187       scalar context, with $a and $b set to successive pairs of values from
188       the KVLIST.
189
190       Returns the first pair of values from the list for which the BLOCK
191       returned true in list context, or an empty list of no such pair was
192       found. In scalar context it returns a simple boolean value, rather than
193       either the key or the value found.
194
195           ( $key, $value ) = pairfirst { $a =~ m/^[[:upper:]]+$/ } @kvlist
196
197       Similar to "grep", "pairfirst" aliases $a and $b to elements of the
198       given list. Any modifications of it by the code block will be visible
199       to the caller.
200
201   pairmap BLOCK KVLIST
202       Similar to perl's "map" keyword, but interprets the given list as an
203       even-sized list of pairs. It invokes the BLOCK multiple times, in list
204       context, with $a and $b set to successive pairs of values from the
205       KVLIST.
206
207       Returns the concatenation of all the values returned by the BLOCK in
208       list context, or the count of the number of items that would have been
209       returned in scalar context.
210
211           @result = pairmap { "The key $a has value $b" } @kvlist
212
213       Similar to "map", "pairmap" aliases $a and $b to elements of the given
214       list. Any modifications of it by the code block will be visible to the
215       caller.
216
217   pairs KVLIST
218       A convenient shortcut to operating on even-sized lists of pairs, this
219       function returns a list of ARRAY references, each containing two items
220       from the given list. It is a more efficient version of
221
222           pairmap { [ $a, $b ] } KVLIST
223
224       It is most convenient to use in a "foreach" loop, for example:
225
226           foreach ( pairs @KVLIST ) {
227              my ( $key, $value ) = @$_;
228              ...
229           }
230
231   pairkeys KVLIST
232       A convenient shortcut to operating on even-sized lists of pairs, this
233       function returns a list of the the first values of each of the pairs in
234       the given list. It is a more efficient version of
235
236           pairmap { $a } KVLIST
237
238   pairvalues KVLIST
239       A convenient shortcut to operating on even-sized lists of pairs, this
240       function returns a list of the the second values of each of the pairs
241       in the given list. It is a more efficient version of
242
243           pairmap { $b } KVLIST
244

OTHER FUNCTIONS

246   shuffle LIST
247       Returns the elements of LIST in a random order
248
249           @cards = shuffle 0..51      # 0..51 in a random order
250

List::SomeUtils FUNCTIONS

252   Junctions
253       Treatment of an empty list
254
255       There are two schools of thought for how to evaluate a junction on an
256       empty list:
257
258       ·   Reduction to an identity (boolean)
259
260       ·   Result is undefined (three-valued)
261
262       In the first case, the result of the junction applied to the empty list
263       is determined by a mathematical reduction to an identity depending on
264       whether the underlying comparison is "or" or "and".  Conceptually:
265
266                           "any are true"      "all are true"
267                           --------------      --------------
268           2 elements:     A || B || 0         A && B && 1
269           1 element:      A || 0              A && 1
270           0 elements:     0                   1
271
272       In the second case, three-value logic is desired, in which a junction
273       applied to an empty list returns "undef" rather than true or false
274
275       Junctions with a "_u" suffix implement three-valued logic.  Those
276       without are boolean.
277
278       all BLOCK LIST
279
280       all_u BLOCK LIST
281
282       Returns a true value if all items in LIST meet the criterion given
283       through BLOCK. Sets $_ for each item in LIST in turn:
284
285         print "All values are non-negative"
286           if all { $_ >= 0 } ($x, $y, $z);
287
288       For an empty LIST, "all" returns true (i.e. no values failed the
289       condition) and "all_u" returns "undef".
290
291       Thus, "all_u(@list)" is equivalent to "@list ? all(@list) : undef".
292
293       Note: because Perl treats "undef" as false, you must check the return
294       value of "all_u" with "defined" or you will get the opposite result of
295       what you expect.
296
297       any BLOCK LIST
298
299       any_u BLOCK LIST
300
301       Returns a true value if any item in LIST meets the criterion given
302       through BLOCK. Sets $_ for each item in LIST in turn:
303
304         print "At least one non-negative value"
305           if any { $_ >= 0 } ($x, $y, $z);
306
307       For an empty LIST, "any" returns false and "any_u" returns "undef".
308
309       Thus, "any_u(@list)" is equivalent to "@list ? any(@list) : undef".
310
311       none BLOCK LIST
312
313       none_u BLOCK LIST
314
315       Logically the negation of "any". Returns a true value if no item in
316       LIST meets the criterion given through BLOCK. Sets $_ for each item in
317       LIST in turn:
318
319         print "No non-negative values"
320           if none { $_ >= 0 } ($x, $y, $z);
321
322       For an empty LIST, "none" returns true (i.e. no values failed the
323       condition) and "none_u" returns "undef".
324
325       Thus, "none_u(@list)" is equivalent to "@list ? none(@list) : undef".
326
327       Note: because Perl treats "undef" as false, you must check the return
328       value of "none_u" with "defined" or you will get the opposite result of
329       what you expect.
330
331       notall BLOCK LIST
332
333       notall_u BLOCK LIST
334
335       Logically the negation of "all". Returns a true value if not all items
336       in LIST meet the criterion given through BLOCK. Sets $_ for each item
337       in LIST in turn:
338
339         print "Not all values are non-negative"
340           if notall { $_ >= 0 } ($x, $y, $z);
341
342       For an empty LIST, "notall" returns false and "notall_u" returns
343       "undef".
344
345       Thus, "notall_u(@list)" is equivalent to "@list ? notall(@list) :
346       undef".
347
348       one BLOCK LIST
349
350       one_u BLOCK LIST
351
352       Returns a true value if precisely one item in LIST meets the criterion
353       given through BLOCK. Sets $_ for each item in LIST in turn:
354
355           print "Precisely one value defined"
356               if one { defined($_) } @list;
357
358       Returns false otherwise.
359
360       For an empty LIST, "one" returns false and "one_u" returns "undef".
361
362       The expression "one BLOCK LIST" is almost equivalent to "1 == true
363       BLOCK LIST", except for short-cutting.  Evaluation of BLOCK will
364       immediately stop at the second true value.
365
366   Transformation
367       apply BLOCK LIST
368
369       Applies BLOCK to each item in LIST and returns a list of the values
370       after BLOCK has been applied. In scalar context, the last element is
371       returned.  This function is similar to "map" but will not modify the
372       elements of the input list:
373
374         my @list = (1 .. 4);
375         my @mult = apply { $_ *= 2 } @list;
376         print "\@list = @list\n";
377         print "\@mult = @mult\n";
378         __END__
379         @list = 1 2 3 4
380         @mult = 2 4 6 8
381
382       Think of it as syntactic sugar for
383
384         for (my @mult = @list) { $_ *= 2 }
385
386       insert_after BLOCK VALUE LIST
387
388       Inserts VALUE after the first item in LIST for which the criterion in
389       BLOCK is true. Sets $_ for each item in LIST in turn.
390
391         my @list = qw/This is a list/;
392         insert_after { $_ eq "a" } "longer" => @list;
393         print "@list";
394         __END__
395         This is a longer list
396
397       insert_after_string STRING VALUE LIST
398
399       Inserts VALUE after the first item in LIST which is equal to STRING.
400
401         my @list = qw/This is a list/;
402         insert_after_string "a", "longer" => @list;
403         print "@list";
404         __END__
405         This is a longer list
406
407       pairwise BLOCK ARRAY1 ARRAY2
408
409       Evaluates BLOCK for each pair of elements in ARRAY1 and ARRAY2 and
410       returns a new list consisting of BLOCK's return values. The two
411       elements are set to $a and $b.  Note that those two are aliases to the
412       original value so changing them will modify the input arrays.
413
414         @a = (1 .. 5);
415         @b = (11 .. 15);
416         @x = pairwise { $a + $b } @a, @b;     # returns 12, 14, 16, 18, 20
417
418         # mesh with pairwise
419         @a = qw/a b c/;
420         @b = qw/1 2 3/;
421         @x = pairwise { ($a, $b) } @a, @b;    # returns a, 1, b, 2, c, 3
422
423       mesh ARRAY1 ARRAY2 [ ARRAY3 ... ]
424
425       zip ARRAY1 ARRAY2 [ ARRAY3 ... ]
426
427       Returns a list consisting of the first elements of each array, then the
428       second, then the third, etc, until all arrays are exhausted.
429
430       Examples:
431
432         @x = qw/a b c d/;
433         @y = qw/1 2 3 4/;
434         @z = mesh @x, @y;         # returns a, 1, b, 2, c, 3, d, 4
435
436         @a = ('x');
437         @b = ('1', '2');
438         @c = qw/zip zap zot/;
439         @d = mesh @a, @b, @c;   # x, 1, zip, undef, 2, zap, undef, undef, zot
440
441       "zip" is an alias for "mesh".
442
443       uniq LIST
444
445       distinct LIST
446
447       Returns a new list by stripping duplicate values in LIST by comparing
448       the values as hash keys, except that undef is considered separate from
449       ''.  The order of elements in the returned list is the same as in LIST.
450       In scalar context, returns the number of unique elements in LIST.
451
452         my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 1 2 3 5 4
453         my $x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 5
454         # returns "Mike", "Michael", "Richard", "Rick"
455         my @n = distinct "Mike", "Michael", "Richard", "Rick", "Michael", "Rick"
456         # returns '', undef, 'S1', A5'
457         my @s = distinct '', undef, 'S1', 'A5'
458         # returns '', undef, 'S1', A5'
459         my @w = uniq undef, '', 'S1', 'A5'
460
461       "distinct" is an alias for "uniq".
462
463       RT#49800 can be used to give feedback about this behavior.
464
465       singleton
466
467       Returns a new list by stripping values in LIST occurring more than once
468       by comparing the values as hash keys, except that undef is considered
469       separate from ''.  The order of elements in the returned list is the
470       same as in LIST.  In scalar context, returns the number of elements
471       occurring only once in LIST.
472
473         my @x = singleton 1,1,2,2,3,4,5 # returns 3 4 5
474
475   Partitioning
476       after BLOCK LIST
477
478       Returns a list of the values of LIST after (and not including) the
479       point where BLOCK returns a true value. Sets $_ for each element in
480       LIST in turn.
481
482         @x = after { $_ % 5 == 0 } (1..9);    # returns 6, 7, 8, 9
483
484       after_incl BLOCK LIST
485
486       Same as "after" but also includes the element for which BLOCK is true.
487
488       before BLOCK LIST
489
490       Returns a list of values of LIST up to (and not including) the point
491       where BLOCK returns a true value. Sets $_ for each element in LIST in
492       turn.
493
494       before_incl BLOCK LIST
495
496       Same as "before" but also includes the element for which BLOCK is true.
497
498       part BLOCK LIST
499
500       Partitions LIST based on the return value of BLOCK which denotes into
501       which partition the current value is put.
502
503       Returns a list of the partitions thusly created. Each partition created
504       is a reference to an array.
505
506         my $i = 0;
507         my @part = part { $i++ % 2 } 1 .. 8;   # returns [1, 3, 5, 7], [2, 4, 6, 8]
508
509       You can have a sparse list of partitions as well where non-set
510       partitions will be undef:
511
512         my @part = part { 2 } 1 .. 10;            # returns undef, undef, [ 1 .. 10 ]
513
514       Be careful with negative values, though:
515
516         my @part = part { -1 } 1 .. 10;
517         __END__
518         Modification of non-creatable array value attempted, subscript -1 ...
519
520       Negative values are only ok when they refer to a partition previously
521       created:
522
523         my @idx  = ( 0, 1, -1 );
524         my $i    = 0;
525         my @part = part { $idx[$++ % 3] } 1 .. 8; # [1, 4, 7], [2, 3, 5, 6, 8]
526
527   Iteration
528       each_array ARRAY1 ARRAY2 ...
529
530       Creates an array iterator to return the elements of the list of arrays
531       ARRAY1, ARRAY2 throughout ARRAYn in turn.  That is, the first time it
532       is called, it returns the first element of each array.  The next time,
533       it returns the second elements.  And so on, until all elements are
534       exhausted.
535
536       This is useful for looping over more than one array at once:
537
538         my $ea = each_array(@a, @b, @c);
539         while ( my ($a, $b, $c) = $ea->() )   { .... }
540
541       The iterator returns the empty list when it reached the end of all
542       arrays.
543
544       If the iterator is passed an argument of '"index"', then it returns the
545       index of the last fetched set of values, as a scalar.
546
547       each_arrayref LIST
548
549       Like each_array, but the arguments are references to arrays, not the
550       plain arrays.
551
552       natatime EXPR, LIST
553
554       Creates an array iterator, for looping over an array in chunks of $n
555       items at a time.  (n at a time, get it?).  An example is probably a
556       better explanation than I could give in words.
557
558       Example:
559
560         my @x = ('a' .. 'g');
561         my $it = natatime 3, @x;
562         while (my @vals = $it->())
563         {
564           print "@vals\n";
565         }
566
567       This prints
568
569         a b c
570         d e f
571         g
572
573   Searching
574       bsearch BLOCK LIST
575
576       Performs a binary search on LIST which must be a sorted list of values.
577       BLOCK must return a negative value if the current element (stored in
578       $_) is smaller, a positive value if it is bigger and zero if it
579       matches.
580
581       Returns a boolean value in scalar context. In list context, it returns
582       the element if it was found, otherwise the empty list.
583
584       bsearchidx BLOCK LIST
585
586       bsearch_index BLOCK LIST
587
588       Performs a binary search on LIST which must be a sorted list of values.
589       BLOCK must return a negative value if the current element (stored in
590       $_) is smaller, a positive value if it is bigger and zero if it
591       matches.
592
593       Returns the index of found element, otherwise "-1".
594
595       "bsearch_index" is an alias for "bsearchidx".
596
597       firstval BLOCK LIST
598
599       first_value BLOCK LIST
600
601       Returns the first element in LIST for which BLOCK evaluates to true.
602       Each element of LIST is set to $_ in turn. Returns "undef" if no such
603       element has been found.
604
605       "first_value" is an alias for "firstval".
606
607       onlyval BLOCK LIST
608
609       only_value BLOCK LIST
610
611       Returns the only element in LIST for which BLOCK evaluates to true.
612       Sets $_ for each item in LIST in turn. Returns "undef" if no such
613       element has been found.
614
615       "only_value" is an alias for "onlyval".
616
617       lastval BLOCK LIST
618
619       last_value BLOCK LIST
620
621       Returns the last value in LIST for which BLOCK evaluates to true. Each
622       element of LIST is set to $_ in turn. Returns "undef" if no such
623       element has been found.
624
625       "last_value" is an alias for "lastval".
626
627       firstres BLOCK LIST
628
629       first_result BLOCK LIST
630
631       Returns the result of BLOCK for the first element in LIST for which
632       BLOCK evaluates to true. Each element of LIST is set to $_ in turn.
633       Returns "undef" if no such element has been found.
634
635       "first_result" is an alias for "firstres".
636
637       onlyres BLOCK LIST
638
639       only_result BLOCK LIST
640
641       Returns the result of BLOCK for the first element in LIST for which
642       BLOCK evaluates to true. Sets $_ for each item in LIST in turn. Returns
643       "undef" if no such element has been found.
644
645       "only_result" is an alias for "onlyres".
646
647       lastres BLOCK LIST
648
649       last_result BLOCK LIST
650
651       Returns the result of BLOCK for the last element in LIST for which
652       BLOCK evaluates to true. Each element of LIST is set to $_ in turn.
653       Returns "undef" if no such element has been found.
654
655       "last_result" is an alias for "lastres".
656
657       indexes BLOCK LIST
658
659       Evaluates BLOCK for each element in LIST (assigned to $_) and returns a
660       list of the indices of those elements for which BLOCK returned a true
661       value. This is just like "grep" only that it returns indices instead of
662       values:
663
664         @x = indexes { $_ % 2 == 0 } (1..10);   # returns 1, 3, 5, 7, 9
665
666       firstidx BLOCK LIST
667
668       first_index BLOCK LIST
669
670       Returns the index of the first element in LIST for which the criterion
671       in BLOCK is true. Sets $_ for each item in LIST in turn:
672
673         my @list = (1, 4, 3, 2, 4, 6);
674         printf "item with index %i in list is 4", firstidx { $_ == 4 } @list;
675         __END__
676         item with index 1 in list is 4
677
678       Returns "-1" if no such item could be found.
679
680       "first_index" is an alias for "firstidx".
681
682       onlyidx BLOCK LIST
683
684       only_index BLOCK LIST
685
686       Returns the index of the only element in LIST for which the criterion
687       in BLOCK is true. Sets $_ for each item in LIST in turn:
688
689           my @list = (1, 3, 4, 3, 2, 4);
690           printf "uniqe index of item 2 in list is %i", onlyidx { $_ == 2 } @list;
691           __END__
692           unique index of item 2 in list is 4
693
694       Returns "-1" if either no such item or more than one of these has been
695       found.
696
697       "only_index" is an alias for "onlyidx".
698
699       lastidx BLOCK LIST
700
701       last_index BLOCK LIST
702
703       Returns the index of the last element in LIST for which the criterion
704       in BLOCK is true. Sets $_ for each item in LIST in turn:
705
706         my @list = (1, 4, 3, 2, 4, 6);
707         printf "item with index %i in list is 4", lastidx { $_ == 4 } @list;
708         __END__
709         item with index 4 in list is 4
710
711       Returns "-1" if no such item could be found.
712
713       "last_index" is an alias for "lastidx".
714
715   Sorting
716       sort_by BLOCK LIST
717
718       Returns the list of values sorted according to the string values
719       returned by the KEYFUNC block or function. A typical use of this may be
720       to sort objects according to the string value of some accessor, such as
721
722         sort_by { $_->name } @people
723
724       The key function is called in scalar context, being passed each value
725       in turn as both $_ and the only argument in the parameters, @_. The
726       values are then sorted according to string comparisons on the values
727       returned.  This is equivalent to
728
729         sort { $a->name cmp $b->name } @people
730
731       except that it guarantees the name accessor will be executed only once
732       per value.  One interesting use-case is to sort strings which may have
733       numbers embedded in them "naturally", rather than lexically.
734
735         sort_by { s/(\d+)/sprintf "%09d", $1/eg; $_ } @strings
736
737       This sorts strings by generating sort keys which zero-pad the embedded
738       numbers to some level (9 digits in this case), helping to ensure the
739       lexical sort puts them in the correct order.
740
741       nsort_by BLOCK LIST
742
743       Similar to sort_by but compares its key values numerically.
744
745   Counting and calculation
746       true BLOCK LIST
747
748       Counts the number of elements in LIST for which the criterion in BLOCK
749       is true.  Sets $_ for  each item in LIST in turn:
750
751         printf "%i item(s) are defined", true { defined($_) } @list;
752
753       false BLOCK LIST
754
755       Counts the number of elements in LIST for which the criterion in BLOCK
756       is false.  Sets $_ for each item in LIST in turn:
757
758         printf "%i item(s) are not defined", false { defined($_) } @list;
759
760       minmax LIST
761
762       Calculates the minimum and maximum of LIST and returns a two element
763       list with the first element being the minimum and the second the
764       maximum. Returns the empty list if LIST was empty.
765
766       The "minmax" algorithm differs from a naive iteration over the list
767       where each element is compared to two values being the so far
768       calculated min and max value in that it only requires 3n/2 - 2
769       comparisons. Thus it is the most efficient possible algorithm.
770
771       However, the Perl implementation of it has some overhead simply due to
772       the fact that there are more lines of Perl code involved. Therefore,
773       LIST needs to be fairly big in order for "minmax" to win over a naive
774       implementation. This limitation does not apply to the XS version.
775
776       mode LIST
777
778       Calculates the most common items in the list and returns them as a
779       list. This is effectively done by string comparisons, so references
780       will be stringified. If they implement string overloading, this will be
781       used.
782
783       If more than one item appears the same number of times in the list, all
784       such items will be returned. For example, the mode of a unique list is
785       the list itself.
786
787       This function always returns a list. That means that in scalar context
788       you get a count indicating the number of modes in the list.
789

List::UtilsBy Functions

791   rev_sort_by
792   rev_nsort_by
793          @vals = rev_sort_by { KEYFUNC } @vals
794
795          @vals = rev_nsort_by { KEYFUNC } @vals
796
797       Since version 0.06.
798
799       Similar to "sort_by" and "nsort_by" but returns the list in the reverse
800       order. Equivalent to
801
802          @vals = reverse sort_by { KEYFUNC } @vals
803
804       except that these functions are slightly more efficient because they
805       avoid the final "reverse" operation.
806
807   max_by
808          $optimal = max_by { KEYFUNC } @vals
809
810          @optimal = max_by { KEYFUNC } @vals
811
812       Returns the (first) value from @vals that gives the numerically largest
813       result from the key function.
814
815          my $tallest = max_by { $_->height } @people
816
817          use File::stat qw( stat );
818          my $newest = max_by { stat($_)->mtime } @files;
819
820       In scalar context, the first maximal value is returned. In list
821       context, a list of all the maximal values is returned. This may be used
822       to obtain positions other than the first, if order is significant.
823
824       If called on an empty list, an empty list is returned.
825
826       For symmetry with the "nsort_by" function, this is also provided under
827       the name "nmax_by" since it behaves numerically.
828
829   min_by
830          $optimal = min_by { KEYFUNC } @vals
831
832          @optimal = min_by { KEYFUNC } @vals
833
834       Similar to "max_by" but returns values which give the numerically
835       smallest result from the key function. Also provided as "nmin_by"
836
837   minmax_by
838          ( $minimal, $maximal ) = minmax_by { KEYFUNC } @vals
839
840       Similar to calling both "min_by" and "max_by" with the same key
841       function on the same list. This version is more efficient than calling
842       the two other functions individually, as it has less work to perform
843       overall. In the case of ties, only the first optimal element found in
844       each case is returned. Also provided as "nminmax_by".
845
846   uniq_by
847          @vals = uniq_by { KEYFUNC } @vals
848
849       Returns a list of the subset of values for which the key function block
850       returns unique values. The first value yielding a particular key is
851       chosen, subsequent values are rejected.
852
853          my @some_fruit = uniq_by { $_->colour } @fruit;
854
855       To select instead the last value per key, reverse the input list. If
856       the order of the results is significant, don't forget to reverse the
857       result as well:
858
859          my @some_fruit = reverse uniq_by { $_->colour } reverse @fruit;
860
861       Because the values returned by the key function are used as hash keys,
862       they ought to either be strings, or at least well-behaved as strings
863       (such as numbers, or object references which overload stringification
864       in a suitable manner).
865
866   partition_by
867          %parts = partition_by { KEYFUNC } @vals
868
869       Returns a key/value list of ARRAY refs containing all the original
870       values distributed according to the result of the key function block.
871       Each value will be an ARRAY ref containing all the values which
872       returned the string from the key function, in their original order.
873
874          my %balls_by_colour = partition_by { $_->colour } @balls;
875
876       Because the values returned by the key function are used as hash keys,
877       they ought to either be strings, or at least well-behaved as strings
878       (such as numbers, or object references which overload stringification
879       in a suitable manner).
880
881   count_by
882          %counts = count_by { KEYFUNC } @vals
883
884       Returns a key/value list of integers, giving the number of times the
885       key function block returned the key, for each value in the list.
886
887          my %count_of_balls = count_by { $_->colour } @balls;
888
889       Because the values returned by the key function are used as hash keys,
890       they ought to either be strings, or at least well-behaved as strings
891       (such as numbers, or object references which overload stringification
892       in a suitable manner).
893
894   zip_by
895          @vals = zip_by { ITEMFUNC } \@arr0, \@arr1, \@arr2,...
896
897       Returns a list of each of the values returned by the function block,
898       when invoked with values from across each each of the given ARRAY
899       references. Each value in the returned list will be the result of the
900       function having been invoked with arguments at that position, from
901       across each of the arrays given.
902
903          my @transposition = zip_by { [ @_ ] } @matrix;
904
905          my @names = zip_by { "$_[1], $_[0]" } \@firstnames, \@surnames;
906
907          print zip_by { "$_[0] => $_[1]\n" } [ keys %hash ], [ values %hash ];
908
909       If some of the arrays are shorter than others, the function will behave
910       as if they had "undef" in the trailing positions. The following two
911       lines are equivalent:
912
913          zip_by { f(@_) } [ 1, 2, 3 ], [ "a", "b" ]
914          f( 1, "a" ), f( 2, "b" ), f( 3, undef )
915
916       The item function is called by "map", so if it returns a list, the
917       entire list is included in the result. This can be useful for example,
918       for generating a hash from two separate lists of keys and values
919
920          my %nums = zip_by { @_ } [qw( one two three )], [ 1, 2, 3 ];
921          # %nums = ( one => 1, two => 2, three => 3 )
922
923       (A function having this behaviour is sometimes called "zipWith", e.g.
924       in Haskell, but that name would not fit the naming scheme used by this
925       module).
926
927   unzip_by
928          $arr0, $arr1, $arr2, ... = unzip_by { ITEMFUNC } @vals
929
930       Returns a list of ARRAY references containing the values returned by
931       the function block, when invoked for each of the values given in the
932       input list.  Each of the returned ARRAY references will contain the
933       values returned at that corresponding position by the function block.
934       That is, the first returned ARRAY reference will contain all the values
935       returned in the first position by the function block, the second will
936       contain all the values from the second position, and so on.
937
938          my ( $firstnames, $lastnames ) = unzip_by { m/^(.*?) (.*)$/ } @names;
939
940       If the function returns lists of differing lengths, the result will be
941       padded with "undef" in the missing elements.
942
943       This function is an inverse of "zip_by", if given a corresponding
944       inverse function.
945
946   extract_by
947          @vals = extract_by { SELECTFUNC } @arr
948
949       Removes elements from the referenced array on which the selection
950       function returns true, and returns a list containing those elements.
951       This function is similar to "grep", except that it modifies the
952       referenced array to remove the selected values from it, leaving only
953       the unselected ones.
954
955          my @red_balls = extract_by { $_->color eq "red" } @balls;
956
957          # Now there are no red balls in the @balls array
958
959       This function modifies a real array, unlike most of the other functions
960       in this module. Because of this, it requires a real array, not just a
961       list.
962
963       This function is implemented by invoking "splice" on the array, not by
964       constructing a new list and assigning it. One result of this is that
965       weak references will not be disturbed.
966
967          extract_by { !defined $_ } @refs;
968
969       will leave weak references weakened in the @refs array, whereas
970
971          @refs = grep { defined $_ } @refs;
972
973       will strengthen them all again.
974
975   extract_first_by
976          $val = extract_first_by { SELECTFUNC } @arr
977
978       A hybrid between "extract_by" and "List::Util::first". Removes the
979       first element from the referenced array on which the selection function
980       returns true, returning it.
981
982       As with "extract_by", this function requires a real array and not just
983       a list, and is also implemented using "splice" so that weak references
984       are not disturbed.
985
986       If this function fails to find a matching element, it will return an
987       empty list in list context. This allows a caller to distinguish the
988       case between no matching element, and the first matching element being
989       "undef".
990
991   weighted_shuffle_by
992          @vals = weighted_shuffle_by { WEIGHTFUNC } @vals
993
994       Returns the list of values shuffled into a random order. The
995       randomisation is not uniform, but weighted by the value returned by the
996       "WEIGHTFUNC". The probability of each item being returned first will be
997       distributed with the distribution of the weights, and so on recursively
998       for the remaining items.
999
1000   bundle_by
1001          @vals = bundle_by { BLOCKFUNC } $number, @vals
1002
1003       Similar to a regular "map" functional, returns a list of the values
1004       returned by "BLOCKFUNC". Values from the input list are given to the
1005       block function in bundles of $number.
1006
1007       If given a list of values whose length does not evenly divide by
1008       $number, the final call will be passed fewer elements than the others.
1009

EXPORTS

1011       This module exports nothing by default. You can import functions by
1012       name, or get everything with the ":all" tag.
1013

SEE ALSO

1015       List::Util,  List::SomeUtils and List::UtilsBy, obviously.
1016
1017       Also see "Util::Any", which unifies many more util modules, and also
1018       lets you rename functions as part of the import.
1019

BUGS

1021       Please report any bugs or feature requests to
1022       "bug-list-allutils@rt.cpan.org", or through the web interface at
1023       <http://rt.cpan.org>.  I will be notified, and then you'll
1024       automatically be notified of progress on your bug as I make changes.
1025
1026       Bugs may be submitted at
1027       <http://rt.cpan.org/Public/Dist/Display.html?Name=List-AllUtils> or via
1028       email to bug-list-allutils@rt.cpan.org <mailto:bug-list-
1029       allutils@rt.cpan.org>.
1030
1031       I am also usually active on IRC as 'autarch' on "irc://irc.perl.org".
1032

SOURCE

1034       The source code repository for List-AllUtils can be found at
1035       <https://github.com/houseabsolute/List-AllUtils>.
1036

DONATIONS

1038       If you'd like to thank me for the work I've done on this module, please
1039       consider making a "donation" to me via PayPal. I spend a lot of free
1040       time creating free software, and would appreciate any support you'd
1041       care to offer.
1042
1043       Please note that I am not suggesting that you must do this in order for
1044       me to continue working on this particular software. I will continue to
1045       do so, inasmuch as I have in the past, for as long as it interests me.
1046
1047       Similarly, a donation made in this way will probably not make me work
1048       on this software much more, unless I get so many donations that I can
1049       consider working on free software full time (let's all have a chuckle
1050       at that together).
1051
1052       To donate, log into PayPal and send money to autarch@urth.org, or use
1053       the button at <http://www.urth.org/~autarch/fs-donation.html>.
1054

AUTHOR

1056       Dave Rolsky <autarch@urth.org>
1057

CONTRIBUTORS

1059       ·   Karen Etheridge <ether@cpan.org>
1060
1061       ·   Ricardo Signes <rjbs@cpan.org>
1062
1063       ·   Yanick Champoux <yanick@babyl.dyndns.org>
1064
1066       This software is Copyright (c) 2018 by Dave Rolsky.
1067
1068       This is free software, licensed under:
1069
1070         The Artistic License 2.0 (GPL Compatible)
1071
1072       The full text of the license can be found in the LICENSE file included
1073       with this distribution.
1074
1075
1076
1077perl v5.30.0                      2019-07-26                 List::AllUtils(3)
Impressum