File Coverage

blib/lib/List/Util.pm
Criterion Covered Total %
statement 0 8 0.0
branch n/a
condition n/a
subroutine 0 1 0.0
pod n/a
total 0 9 0.0


line stmt bran cond sub pod time code
1             # Copyright (c) 1997-2009 Graham Barr . All rights reserved.
2             # This program is free software; you can redistribute it and/or
3             # modify it under the same terms as Perl itself.
4             #
5             # Maintained since 2013 by Paul Evans
6              
7             package List::Util;
8              
9             use strict;
10             use warnings;
11             require Exporter;
12              
13             our @ISA = qw(Exporter);
14             our @EXPORT_OK = qw(
15             all any first min max minstr maxstr none notall product reduce sum sum0 shuffle uniq uniqnum uniqstr
16             pairs unpairs pairkeys pairvalues pairmap pairgrep pairfirst
17             );
18             our $VERSION = "1.46_01";
19             $VERSION = eval $VERSION;
20              
21             # List::Util can be upgraded, leaving Scalar::Util and Sub::Util at their
22             # pre-split version. Those versions relied on List::Util to provide
23             # their implementation in XS. We need to detect this situation and load the old
24             # compiled List::Util code that was left behind by our old version. For newer
25             # versions of those modules (and this module), we need to localize the stashes
26             # while loading so the new subs aren't overwritten.
27             {
28             require Scalar::Util;
29             eval { require Sub::Util };
30              
31             # New Scalar::Util does not load List::Util. If its $VERSION is false (after
32             # loading it), then it's a pre-split version of Scalar::Util loading us, and
33             # it is not fully loaded yet.
34             my $scalar_v = $Scalar::Util::VERSION || 0;
35             my $sub_v = $Sub::Util::VERSION || 0;
36              
37             if (
38             ( $scalar_v <= 1.45 )
39             || ( $sub_v && $sub_v <= 1.45 )
40             ) {
41             local %Scalar::Util:: if $scalar_v > 1.45;
42             local %Sub::Util:: if $sub_v > 1.45;
43             @Scalar::Util::EXPORT_FAIL = () if $scalar_v <= 1.45;
44              
45             # localizing the List::Util stash will break XSLoader::load, so we save and
46             # clear it manually. Using this mechanism on Scalar::Util/Sub::Util would
47             # break sub names.
48             my %list_stash = %List::Util::;
49             %List::Util:: = ();
50             my $success = eval {
51             local $SIG{__DIE__};
52             require XSLoader;
53             XSLoader::load(__PACKAGE__);
54             1;
55             };
56             my $e = $@;
57             %List::Util:: = %list_stash;
58             if ($scalar_v <= 1.45) {
59             no strict 'refs';
60             push @Scalar::Util::EXPORT_FAIL,
61             grep !defined &{"Scalar::Util::$_"},
62             qw(weaken isweak isvstring);
63             }
64             die $e unless $success;
65             }
66             }
67              
68             if (eval { require List::Util::XS; } && $List::Util::XS::VERSION > 1.45) {
69             List::Util::XS->import(@EXPORT_OK);
70             }
71             else {
72             require List::Util::PP;
73             List::Util::PP->import(@EXPORT_OK);
74             }
75              
76             sub import
77             {
78 0     0     my $pkg = caller;
79              
80             # (RT88848) Touch the caller's $a and $b, to avoid the warning of
81             # Name "main::a" used only once: possible typo" warning
82             no strict 'refs';
83 0           ${"${pkg}::a"} = ${"${pkg}::a"};
  0            
  0            
84 0           ${"${pkg}::b"} = ${"${pkg}::b"};
  0            
  0            
85              
86 0           goto &Exporter::import;
87             }
88              
89             =head1 NAME
90              
91             List::Util - A selection of general-utility list subroutines
92              
93             =head1 SYNOPSIS
94              
95             use List::Util qw(
96             reduce any all none notall first
97              
98             max maxstr min minstr product sum sum0
99              
100             pairs unpairs pairkeys pairvalues pairfirst pairgrep pairmap
101              
102             shuffle uniq uniqnum uniqstr
103             );
104              
105             =head1 DESCRIPTION
106              
107             C contains a selection of subroutines that people have expressed
108             would be nice to have in the perl core, but the usage would not really be high
109             enough to warrant the use of a keyword, and the size so small such that being
110             individual extensions would be wasteful.
111              
112             By default C does not export any subroutines.
113              
114             =cut
115              
116             =head1 LIST-REDUCTION FUNCTIONS
117              
118             The following set of functions all reduce a list down to a single value.
119              
120             =cut
121              
122             =head2 reduce
123              
124             $result = reduce { BLOCK } @list
125              
126             Reduces C<@list> by calling C in a scalar context multiple times,
127             setting C<$a> and C<$b> each time. The first call will be with C<$a> and C<$b>
128             set to the first two elements of the list, subsequent calls will be done by
129             setting C<$a> to the result of the previous call and C<$b> to the next element
130             in the list.
131              
132             Returns the result of the last call to the C. If C<@list> is empty then
133             C is returned. If C<@list> only contains one element then that element
134             is returned and C is not executed.
135              
136             The following examples all demonstrate how C could be used to implement
137             the other list-reduction functions in this module. (They are not in fact
138             implemented like this, but instead in a more efficient manner in individual C
139             functions).
140              
141             $foo = reduce { defined($a) ? $a :
142             $code->(local $_ = $b) ? $b :
143             undef } undef, @list # first
144              
145             $foo = reduce { $a > $b ? $a : $b } 1..10 # max
146             $foo = reduce { $a gt $b ? $a : $b } 'A'..'Z' # maxstr
147             $foo = reduce { $a < $b ? $a : $b } 1..10 # min
148             $foo = reduce { $a lt $b ? $a : $b } 'aa'..'zz' # minstr
149             $foo = reduce { $a + $b } 1 .. 10 # sum
150             $foo = reduce { $a . $b } @bar # concat
151              
152             $foo = reduce { $a || $code->(local $_ = $b) } 0, @bar # any
153             $foo = reduce { $a && $code->(local $_ = $b) } 1, @bar # all
154             $foo = reduce { $a && !$code->(local $_ = $b) } 1, @bar # none
155             $foo = reduce { $a || !$code->(local $_ = $b) } 0, @bar # notall
156             # Note that these implementations do not fully short-circuit
157              
158             If your algorithm requires that C produce an identity value, then make
159             sure that you always pass that identity value as the first argument to prevent
160             C being returned
161              
162             $foo = reduce { $a + $b } 0, @values; # sum with 0 identity value
163              
164             The above example code blocks also suggest how to use C to build a
165             more efficient combined version of one of these basic functions and a C
166             block. For example, to find the total length of the all the strings in a list,
167             we could use
168              
169             $total = sum map { length } @strings;
170              
171             However, this produces a list of temporary integer values as long as the
172             original list of strings, only to reduce it down to a single value again. We
173             can compute the same result more efficiently by using C with a code
174             block that accumulates lengths by writing this instead as:
175              
176             $total = reduce { $a + length $b } 0, @strings
177              
178             The remaining list-reduction functions are all specialisations of this generic
179             idea.
180              
181             =head2 any
182              
183             my $bool = any { BLOCK } @list;
184              
185             I
186              
187             Similar to C in that it evaluates C setting C<$_> to each element
188             of C<@list> in turn. C returns true if any element makes the C
189             return a true value. If C never returns true or C<@list> was empty then
190             it returns false.
191              
192             Many cases of using C in a conditional can be written using C
193             instead, as it can short-circuit after the first true result.
194              
195             if( any { length > 10 } @strings ) {
196             # at least one string has more than 10 characters
197             }
198              
199             =head2 all
200              
201             my $bool = all { BLOCK } @list;
202              
203             I
204              
205             Similar to L, except that it requires all elements of the C<@list> to
206             make the C return true. If any element returns false, then it returns
207             false. If the C never returns false or the C<@list> was empty then it
208             returns true.
209              
210             =head2 none
211              
212             =head2 notall
213              
214             my $bool = none { BLOCK } @list;
215              
216             my $bool = notall { BLOCK } @list;
217              
218             I
219              
220             Similar to L and L, but with the return sense inverted. C
221             returns true only if no value in the C<@list> causes the C to return
222             true, and C returns true only if not all of the values do.
223              
224             =head2 first
225              
226             my $val = first { BLOCK } @list;
227              
228             Similar to C in that it evaluates C setting C<$_> to each element
229             of C<@list> in turn. C returns the first element where the result from
230             C is a true value. If C never returns true or C<@list> was empty
231             then C is returned.
232              
233             $foo = first { defined($_) } @list # first defined value in @list
234             $foo = first { $_ > $value } @list # first value in @list which
235             # is greater than $value
236              
237             =head2 max
238              
239             my $num = max @list;
240              
241             Returns the entry in the list with the highest numerical value. If the list is
242             empty then C is returned.
243              
244             $foo = max 1..10 # 10
245             $foo = max 3,9,12 # 12
246             $foo = max @bar, @baz # whatever
247              
248             =head2 maxstr
249              
250             my $str = maxstr @list;
251              
252             Similar to L, but treats all the entries in the list as strings and
253             returns the highest string as defined by the C operator. If the list is
254             empty then C is returned.
255              
256             $foo = maxstr 'A'..'Z' # 'Z'
257             $foo = maxstr "hello","world" # "world"
258             $foo = maxstr @bar, @baz # whatever
259              
260             =head2 min
261              
262             my $num = min @list;
263              
264             Similar to L but returns the entry in the list with the lowest numerical
265             value. If the list is empty then C is returned.
266              
267             $foo = min 1..10 # 1
268             $foo = min 3,9,12 # 3
269             $foo = min @bar, @baz # whatever
270              
271             =head2 minstr
272              
273             my $str = minstr @list;
274              
275             Similar to L, but treats all the entries in the list as strings and
276             returns the lowest string as defined by the C operator. If the list is
277             empty then C is returned.
278              
279             $foo = minstr 'A'..'Z' # 'A'
280             $foo = minstr "hello","world" # "hello"
281             $foo = minstr @bar, @baz # whatever
282              
283             =head2 product
284              
285             my $num = product @list;
286              
287             I
288              
289             Returns the numerical product of all the elements in C<@list>. If C<@list> is
290             empty then C<1> is returned.
291              
292             $foo = product 1..10 # 3628800
293             $foo = product 3,9,12 # 324
294              
295             =head2 sum
296              
297             my $num_or_undef = sum @list;
298              
299             Returns the numerical sum of all the elements in C<@list>. For backwards
300             compatibility, if C<@list> is empty then C is returned.
301              
302             $foo = sum 1..10 # 55
303             $foo = sum 3,9,12 # 24
304             $foo = sum @bar, @baz # whatever
305              
306             =head2 sum0
307              
308             my $num = sum0 @list;
309              
310             I
311              
312             Similar to L, except this returns 0 when given an empty list, rather
313             than C.
314              
315             =cut
316              
317             =head1 KEY/VALUE PAIR LIST FUNCTIONS
318              
319             The following set of functions, all inspired by L, consume an
320             even-sized list of pairs. The pairs may be key/value associations from a hash,
321             or just a list of values. The functions will all preserve the original ordering
322             of the pairs, and will not be confused by multiple pairs having the same "key"
323             value - nor even do they require that the first of each pair be a plain string.
324              
325             B: At the time of writing, the following C functions that take a
326             block do not modify the value of C<$_> within the block, and instead operate
327             using the C<$a> and C<$b> globals instead. This has turned out to be a poor
328             design, as it precludes the ability to provide a C function. Better
329             would be to pass pair-like objects as 2-element array references in C<$_>, in
330             a style similar to the return value of the C function. At some future
331             version this behaviour may be added.
332              
333             Until then, users are alerted B to rely on the value of C<$_> remaining
334             unmodified between the outside and the inside of the control block. In
335             particular, the following example is B:
336              
337             my @kvlist = ...
338              
339             foreach (qw( some keys here )) {
340             my @items = pairgrep { $a eq $_ } @kvlist;
341             ...
342             }
343              
344             Instead, write this using a lexical variable:
345              
346             foreach my $key (qw( some keys here )) {
347             my @items = pairgrep { $a eq $key } @kvlist;
348             ...
349             }
350              
351             =cut
352              
353             =head2 pairs
354              
355             my @pairs = pairs @kvlist;
356              
357             I
358              
359             A convenient shortcut to operating on even-sized lists of pairs, this function
360             returns a list of C references, each containing two items from the
361             given list. It is a more efficient version of
362              
363             @pairs = pairmap { [ $a, $b ] } @kvlist
364              
365             It is most convenient to use in a C loop, for example:
366              
367             foreach my $pair ( pairs @kvlist ) {
368             my ( $key, $value ) = @$pair;
369             ...
370             }
371              
372             Since version C<1.39> these C references are blessed objects,
373             recognising the two methods C and C. The following code is
374             equivalent:
375              
376             foreach my $pair ( pairs @kvlist ) {
377             my $key = $pair->key;
378             my $value = $pair->value;
379             ...
380             }
381              
382             =head2 unpairs
383              
384             my @kvlist = unpairs @pairs
385              
386             I
387              
388             The inverse function to C; this function takes a list of C
389             references containing two elements each, and returns a flattened list of the
390             two values from each of the pairs, in order. This is notionally equivalent to
391              
392             my @kvlist = map { @{$_}[0,1] } @pairs
393              
394             except that it is implemented more efficiently internally. Specifically, for
395             any input item it will extract exactly two values for the output list; using
396             C if the input array references are short.
397              
398             Between C and C, a higher-order list function can be used to
399             operate on the pairs as single scalars; such as the following near-equivalents
400             of the other C higher-order functions:
401              
402             @kvlist = unpairs grep { FUNC } pairs @kvlist
403             # Like pairgrep, but takes $_ instead of $a and $b
404              
405             @kvlist = unpairs map { FUNC } pairs @kvlist
406             # Like pairmap, but takes $_ instead of $a and $b
407              
408             Note however that these versions will not behave as nicely in scalar context.
409              
410             Finally, this technique can be used to implement a sort on a keyvalue pair
411             list; e.g.:
412              
413             @kvlist = unpairs sort { $a->key cmp $b->key } pairs @kvlist
414              
415             =head2 pairkeys
416              
417             my @keys = pairkeys @kvlist;
418              
419             I
420              
421             A convenient shortcut to operating on even-sized lists of pairs, this function
422             returns a list of the the first values of each of the pairs in the given list.
423             It is a more efficient version of
424              
425             @keys = pairmap { $a } @kvlist
426              
427             =head2 pairvalues
428              
429             my @values = pairvalues @kvlist;
430              
431             I
432              
433             A convenient shortcut to operating on even-sized lists of pairs, this function
434             returns a list of the the second values of each of the pairs in the given list.
435             It is a more efficient version of
436              
437             @values = pairmap { $b } @kvlist
438              
439             =head2 pairgrep
440              
441             my @kvlist = pairgrep { BLOCK } @kvlist;
442              
443             my $count = pairgrep { BLOCK } @kvlist;
444              
445             I
446              
447             Similar to perl's C keyword, but interprets the given list as an
448             even-sized list of pairs. It invokes the C multiple times, in scalar
449             context, with C<$a> and C<$b> set to successive pairs of values from the
450             C<@kvlist>.
451              
452             Returns an even-sized list of those pairs for which the C returned true
453             in list context, or the count of the B in scalar context.
454             (Note, therefore, in scalar context that it returns a number half the size of
455             the count of items it would have returned in list context).
456              
457             @subset = pairgrep { $a =~ m/^[[:upper:]]+$/ } @kvlist
458              
459             As with C aliasing C<$_> to list elements, C aliases C<$a> and
460             C<$b> to elements of the given list. Any modifications of it by the code block
461             will be visible to the caller.
462              
463             =head2 pairfirst
464              
465             my ( $key, $val ) = pairfirst { BLOCK } @kvlist;
466              
467             my $found = pairfirst { BLOCK } @kvlist;
468              
469             I
470              
471             Similar to the L function, but interprets the given list as an
472             even-sized list of pairs. It invokes the C multiple times, in scalar
473             context, with C<$a> and C<$b> set to successive pairs of values from the
474             C<@kvlist>.
475              
476             Returns the first pair of values from the list for which the C returned
477             true in list context, or an empty list of no such pair was found. In scalar
478             context it returns a simple boolean value, rather than either the key or the
479             value found.
480              
481             ( $key, $value ) = pairfirst { $a =~ m/^[[:upper:]]+$/ } @kvlist
482              
483             As with C aliasing C<$_> to list elements, C aliases C<$a> and
484             C<$b> to elements of the given list. Any modifications of it by the code block
485             will be visible to the caller.
486              
487             =head2 pairmap
488              
489             my @list = pairmap { BLOCK } @kvlist;
490              
491             my $count = pairmap { BLOCK } @kvlist;
492              
493             I
494              
495             Similar to perl's C keyword, but interprets the given list as an
496             even-sized list of pairs. It invokes the C multiple times, in list
497             context, with C<$a> and C<$b> set to successive pairs of values from the
498             C<@kvlist>.
499              
500             Returns the concatenation of all the values returned by the C in list
501             context, or the count of the number of items that would have been returned in
502             scalar context.
503              
504             @result = pairmap { "The key $a has value $b" } @kvlist
505              
506             As with C aliasing C<$_> to list elements, C aliases C<$a> and
507             C<$b> to elements of the given list. Any modifications of it by the code block
508             will be visible to the caller.
509              
510             See L for a known-bug with C, and a workaround.
511              
512             =cut
513              
514             =head1 OTHER FUNCTIONS
515              
516             =cut
517              
518             =head2 shuffle
519              
520             my @values = shuffle @values;
521              
522             Returns the values of the input in a random order
523              
524             @cards = shuffle 0..51 # 0..51 in a random order
525              
526             =head2 uniq
527              
528             my @subset = uniq @values
529              
530             I
531              
532             Filters a list of values to remove subsequent duplicates, as judged by a
533             DWIM-ish string equality or C test. Preserves the order of unique
534             elements, and retains the first value of any duplicate set.
535              
536             my $count = uniq @values
537              
538             In scalar context, returns the number of elements that would have been
539             returned as a list.
540              
541             The C value is treated by this function as distinct from the empty
542             string, and no warning will be produced. It is left as-is in the returned
543             list. Subsequent C values are still considered identical to the first,
544             and will be removed.
545              
546             =head2 uniqnum
547              
548             my @subset = uniqnum @values
549              
550             I
551              
552             Filters a list of values to remove subsequent duplicates, as judged by a
553             numerical equality test. Preserves the order of unique elements, and retains
554             the first value of any duplicate set.
555              
556             my $count = uniqnum @values
557              
558             In scalar context, returns the number of elements that would have been
559             returned as a list.
560              
561             Note that C is treated much as other numerical operations treat it; it
562             compares equal to zero but additionally produces a warning if such warnings
563             are enabled (C). In addition, an C in
564             the returned list is coerced into a numerical zero, so that the entire list of
565             values returned by C are well-behaved as numbers.
566              
567             Note also that multiple IEEE C values are treated as duplicates of
568             each other, regardless of any differences in their payloads, and despite
569             the fact that C<< 0+'NaN' == 0+'NaN' >> yields false.
570              
571             =head2 uniqstr
572              
573             my @subset = uniqstr @values
574              
575             I
576              
577             Filters a list of values to remove subsequent duplicates, as judged by a
578             string equality test. Preserves the order of unique elements, and retains the
579             first value of any duplicate set.
580              
581             my $count = uniqstr @values
582              
583             In scalar context, returns the number of elements that would have been
584             returned as a list.
585              
586             Note that C is treated much as other string operations treat it; it
587             compares equal to the empty string but additionally produces a warning if such
588             warnings are enabled (C). In addition, an
589             C in the returned list is coerced into an empty string, so that the
590             entire list of values returned by C are well-behaved as strings.
591              
592             =cut
593              
594             =head1 KNOWN BUGS
595              
596             =head2 RT #95409
597              
598             L
599              
600             If the block of code given to L contains lexical variables that are
601             captured by a returned closure, and the closure is executed after the block
602             has been re-used for the next iteration, these lexicals will not see the
603             correct values. For example:
604              
605             my @subs = pairmap {
606             my $var = "$a is $b";
607             sub { print "$var\n" };
608             } one => 1, two => 2, three => 3;
609              
610             $_->() for @subs;
611              
612             Will incorrectly print
613              
614             three is 3
615             three is 3
616             three is 3
617              
618             This is due to the performance optimisation of using C for the code
619             block, which means that fresh SVs do not get allocated for each call to the
620             block. Instead, the same SV is re-assigned for each iteration, and all the
621             closures will share the value seen on the final iteration.
622              
623             To work around this bug, surround the code with a second set of braces. This
624             creates an inner block that defeats the C logic, and does get fresh
625             SVs allocated each time:
626              
627             my @subs = pairmap {
628             {
629             my $var = "$a is $b";
630             sub { print "$var\n"; }
631             }
632             } one => 1, two => 2, three => 3;
633              
634             This bug only affects closures that are generated by the block but used
635             afterwards. Lexical variables that are only used during the lifetime of the
636             block's execution will take their individual values for each invocation, as
637             normal.
638              
639             =head2 uniqnum() on oversized bignums
640              
641             Due to the way that C compares numbers, it cannot distinguish
642             differences between bignums (especially bigints) that are too large to fit in
643             the native platform types. For example,
644              
645             my $x = Math::BigInt->new( "1" x 100 );
646             my $y = $x + 1;
647              
648             say for uniqnum( $x, $y );
649              
650             Will print just the value of C<$x>, believing that C<$y> is a numerically-
651             equivalent value. This bug does not affect C, which will correctly
652             observe that the two values stringify to different strings.
653              
654             =head1 SUGGESTED ADDITIONS
655              
656             The following are additions that have been requested, but I have been reluctant
657             to add due to them being very simple to implement in perl
658              
659             # How many elements are true
660              
661             sub true { scalar grep { $_ } @_ }
662              
663             # How many elements are false
664              
665             sub false { scalar grep { !$_ } @_ }
666              
667             =head1 SEE ALSO
668              
669             L
670              
671             =head1 COPYRIGHT
672              
673             Copyright (c) 1997-2007 Graham Barr . All rights reserved.
674             This program is free software; you can redistribute it and/or
675             modify it under the same terms as Perl itself.
676              
677             Recent additions and current maintenance by
678             Paul Evans, .
679              
680             =cut
681              
682             1;