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