This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fix Scalar-List-Utils build on Windows; patch sent upstream
[perl5.git] / cpan / Scalar-List-Utils / lib / List / Util.pm
CommitLineData
2ff28616 1# Copyright (c) 1997-2009 Graham Barr <gbarr@pobox.com>. All rights reserved.
f4a2945e
JH
2# This program is free software; you can redistribute it and/or
3# modify it under the same terms as Perl itself.
2ff28616 4#
e99e4210 5# Maintained since 2013 by Paul Evans <leonerd@leonerd.org.uk>
f4a2945e
JH
6
7package List::Util;
8
82f35e8b 9use strict;
f4a2945e
JH
10require Exporter;
11
3630f57e 12our @ISA = qw(Exporter);
52102bb4 13our @EXPORT_OK = qw(
98eca5fa 14 all any first min max minstr maxstr none notall product reduce sum sum0 shuffle
3d58dd24 15 pairs unpairs pairkeys pairvalues pairmap pairgrep pairfirst
52102bb4 16);
869a9612 17our $VERSION = "1.42_01";
3630f57e 18our $XS_VERSION = $VERSION;
60f3865b 19$VERSION = eval $VERSION;
f4a2945e 20
3630f57e
CBW
21require XSLoader;
22XSLoader::load('List::Util', $XS_VERSION);
09c2a9b8 23
52102bb4
SH
24sub import
25{
26 my $pkg = caller;
27
28 # (RT88848) Touch the caller's $a and $b, to avoid the warning of
29 # Name "main::a" used only once: possible typo" warning
30 no strict 'refs';
31 ${"${pkg}::a"} = ${"${pkg}::a"};
32 ${"${pkg}::b"} = ${"${pkg}::b"};
33
34 goto &Exporter::import;
35}
36
b823713c
CBW
37# For objects returned by pairs()
38sub List::Util::_Pair::key { shift->[0] }
39sub List::Util::_Pair::value { shift->[1] }
40
f4a2945e
JH
411;
42
43__END__
44
45=head1 NAME
46
47List::Util - A selection of general-utility list subroutines
48
49=head1 SYNOPSIS
50
c29e891d 51 use List::Util qw(first max maxstr min minstr reduce shuffle sum);
f4a2945e
JH
52
53=head1 DESCRIPTION
54
8c167fd9
CBW
55C<List::Util> contains a selection of subroutines that people have expressed
56would be nice to have in the perl core, but the usage would not really be high
57enough to warrant the use of a keyword, and the size so small such that being
58individual extensions would be wasteful.
f4a2945e 59
6a9ebaf3 60By default C<List::Util> does not export any subroutines.
f4a2945e 61
6a9ebaf3
SH
62=cut
63
64=head1 LIST-REDUCTION FUNCTIONS
65
66The following set of functions all reduce a list down to a single value.
67
68=cut
69
8c167fd9 70=head2 $result = reduce { BLOCK } @list
6a9ebaf3 71
8c167fd9
CBW
72Reduces C<@list> by calling C<BLOCK> in a scalar context multiple times,
73setting C<$a> and C<$b> each time. The first call will be with C<$a> and C<$b>
74set to the first two elements of the list, subsequent calls will be done by
75setting C<$a> to the result of the previous call and C<$b> to the next element
76in the list.
6a9ebaf3 77
8c167fd9
CBW
78Returns the result of the last call to the C<BLOCK>. If C<@list> is empty then
79C<undef> is returned. If C<@list> only contains one element then that element
80is returned and C<BLOCK> is not executed.
f4a2945e 81
8c167fd9
CBW
82The following examples all demonstrate how C<reduce> could be used to implement
83the other list-reduction functions in this module. (They are not in fact
84implemented like this, but instead in a more efficient manner in individual C
85functions).
e99e4210
SH
86
87 $foo = reduce { defined($a) ? $a :
88 $code->(local $_ = $b) ? $b :
89 undef } undef, @list # first
90
91 $foo = reduce { $a > $b ? $a : $b } 1..10 # max
92 $foo = reduce { $a gt $b ? $a : $b } 'A'..'Z' # maxstr
6a9ebaf3
SH
93 $foo = reduce { $a < $b ? $a : $b } 1..10 # min
94 $foo = reduce { $a lt $b ? $a : $b } 'aa'..'zz' # minstr
95 $foo = reduce { $a + $b } 1 .. 10 # sum
96 $foo = reduce { $a . $b } @bar # concat
97
e99e4210
SH
98 $foo = reduce { $a || $code->(local $_ = $b) } 0, @bar # any
99 $foo = reduce { $a && $code->(local $_ = $b) } 1, @bar # all
100 $foo = reduce { $a && !$code->(local $_ = $b) } 1, @bar # none
101 $foo = reduce { $a || !$code->(local $_ = $b) } 0, @bar # notall
102 # Note that these implementations do not fully short-circuit
103
8c167fd9
CBW
104If your algorithm requires that C<reduce> produce an identity value, then make
105sure that you always pass that identity value as the first argument to prevent
6a9ebaf3
SH
106C<undef> being returned
107
108 $foo = reduce { $a + $b } 0, @values; # sum with 0 identity value
109
8c167fd9
CBW
110The remaining list-reduction functions are all specialisations of this generic
111idea.
6a9ebaf3 112
d81c2d6a
CBW
113=head2 any
114
115 my $bool = any { BLOCK } @list;
52102bb4 116
b823713c
CBW
117I<Since version 1.33.>
118
8c167fd9
CBW
119Similar to C<grep> in that it evaluates C<BLOCK> setting C<$_> to each element
120of C<@list> in turn. C<any> returns true if any element makes the C<BLOCK>
121return a true value. If C<BLOCK> never returns true or C<@list> was empty then
122it returns false.
52102bb4
SH
123
124Many cases of using C<grep> in a conditional can be written using C<any>
125instead, as it can short-circuit after the first true result.
126
127 if( any { length > 10 } @strings ) {
128 # at least one string has more than 10 characters
129 }
130
d81c2d6a
CBW
131=head2 all
132
133 my $bool = all { BLOCK } @list;
52102bb4 134
b823713c
CBW
135I<Since version 1.33.>
136
d81c2d6a
CBW
137Similar to L</any>, except that it requires all elements of the C<@list> to
138make the C<BLOCK> return true. If any element returns false, then it returns
139false. If the C<BLOCK> never returns false or the C<@list> was empty then it
140returns true.
141
142=head2 none
52102bb4 143
d81c2d6a 144=head2 notall
52102bb4 145
d81c2d6a
CBW
146 my $bool = none { BLOCK } @list;
147
148 my $bool = notall { BLOCK } @list;
52102bb4 149
b823713c
CBW
150I<Since version 1.33.>
151
d81c2d6a
CBW
152Similar to L</any> and L</all>, but with the return sense inverted. C<none>
153returns true only if no value in the C<@list> causes the C<BLOCK> to return
154true, and C<notall> returns true only if not all of the values do.
155
156=head2 first
52102bb4 157
d81c2d6a 158 my $val = first { BLOCK } @list;
f4a2945e 159
8c167fd9
CBW
160Similar to C<grep> in that it evaluates C<BLOCK> setting C<$_> to each element
161of C<@list> in turn. C<first> returns the first element where the result from
162C<BLOCK> is a true value. If C<BLOCK> never returns true or C<@list> was empty
163then C<undef> is returned.
f4a2945e
JH
164
165 $foo = first { defined($_) } @list # first defined value in @list
166 $foo = first { $_ > $value } @list # first value in @list which
167 # is greater than $value
c29e891d 168
d81c2d6a
CBW
169=head2 max
170
171 my $num = max @list;
f4a2945e 172
8c167fd9
CBW
173Returns the entry in the list with the highest numerical value. If the list is
174empty then C<undef> is returned.
f4a2945e
JH
175
176 $foo = max 1..10 # 10
177 $foo = max 3,9,12 # 12
178 $foo = max @bar, @baz # whatever
179
d81c2d6a
CBW
180=head2 maxstr
181
182 my $str = maxstr @list;
f4a2945e 183
d81c2d6a 184Similar to L</max>, but treats all the entries in the list as strings and
8c167fd9
CBW
185returns the highest string as defined by the C<gt> operator. If the list is
186empty then C<undef> is returned.
c29e891d
GB
187
188 $foo = maxstr 'A'..'Z' # 'Z'
f4a2945e
JH
189 $foo = maxstr "hello","world" # "world"
190 $foo = maxstr @bar, @baz # whatever
191
d81c2d6a
CBW
192=head2 min
193
194 my $num = min @list;
f4a2945e 195
d81c2d6a 196Similar to L</max> but returns the entry in the list with the lowest numerical
8c167fd9 197value. If the list is empty then C<undef> is returned.
f4a2945e
JH
198
199 $foo = min 1..10 # 1
200 $foo = min 3,9,12 # 3
201 $foo = min @bar, @baz # whatever
202
d81c2d6a 203=head2 minstr
f4a2945e 204
d81c2d6a
CBW
205 my $str = minstr @list;
206
207Similar to L</min>, but treats all the entries in the list as strings and
8c167fd9
CBW
208returns the lowest string as defined by the C<lt> operator. If the list is
209empty then C<undef> is returned.
f4a2945e 210
c29e891d
GB
211 $foo = minstr 'A'..'Z' # 'A'
212 $foo = minstr "hello","world" # "hello"
213 $foo = minstr @bar, @baz # whatever
f4a2945e 214
d81c2d6a
CBW
215=head2 product
216
217 my $num = product @list;
98eca5fa 218
b823713c
CBW
219I<Since version 1.35.>
220
8c167fd9
CBW
221Returns the numerical product of all the elements in C<@list>. If C<@list> is
222empty then C<1> is returned.
98eca5fa
SH
223
224 $foo = product 1..10 # 3628800
225 $foo = product 3,9,12 # 324
226
d81c2d6a
CBW
227=head2 sum
228
229 my $num_or_undef = sum @list;
6a9ebaf3 230
8c167fd9
CBW
231Returns the numerical sum of all the elements in C<@list>. For backwards
232compatibility, if C<@list> is empty then C<undef> is returned.
6a9ebaf3
SH
233
234 $foo = sum 1..10 # 55
235 $foo = sum 3,9,12 # 24
236 $foo = sum @bar, @baz # whatever
237
d81c2d6a
CBW
238=head2 sum0
239
240 my $num = sum0 @list;
6a9ebaf3 241
b823713c
CBW
242I<Since version 1.26.>
243
d81c2d6a
CBW
244Similar to L</sum>, except this returns 0 when given an empty list, rather
245than C<undef>.
6a9ebaf3
SH
246
247=cut
248
249=head1 KEY/VALUE PAIR LIST FUNCTIONS
250
8c167fd9
CBW
251The following set of functions, all inspired by L<List::Pairwise>, consume an
252even-sized list of pairs. The pairs may be key/value associations from a hash,
253or just a list of values. The functions will all preserve the original ordering
254of the pairs, and will not be confused by multiple pairs having the same "key"
255value - nor even do they require that the first of each pair be a plain string.
6a9ebaf3 256
3d58dd24
SH
257B<NOTE>: At the time of writing, the following C<pair*> functions that take a
258block do not modify the value of C<$_> within the block, and instead operate
259using the C<$a> and C<$b> globals instead. This has turned out to be a poor
260design, as it precludes the ability to provide a C<pairsort> function. Better
261would be to pass pair-like objects as 2-element array references in C<$_>, in
262a style similar to the return value of the C<pairs> function. At some future
263version this behaviour may be added.
264
265Until then, users are alerted B<NOT> to rely on the value of C<$_> remaining
266unmodified between the outside and the inside of the control block. In
267particular, the following example is B<UNSAFE>:
268
269 my @kvlist = ...
270
271 foreach (qw( some keys here )) {
272 my @items = pairgrep { $a eq $_ } @kvlist;
273 ...
274 }
275
276Instead, write this using a lexical variable:
277
278 foreach my $key (qw( some keys here )) {
279 my @items = pairgrep { $a eq $key } @kvlist;
280 ...
281 }
282
6a9ebaf3
SH
283=cut
284
3d58dd24
SH
285=head2 pairs
286
287 my @pairs = pairs @kvlist;
288
289I<Since version 1.29.>
290
291A convenient shortcut to operating on even-sized lists of pairs, this function
292returns a list of ARRAY references, each containing two items from the given
293list. It is a more efficient version of
294
295 @pairs = pairmap { [ $a, $b ] } @kvlist
296
297It is most convenient to use in a C<foreach> loop, for example:
298
299 foreach my $pair ( pairs @KVLIST ) {
300 my ( $key, $value ) = @$pair;
301 ...
302 }
303
304Since version C<1.39> these ARRAY references are blessed objects, recognising
305the two methods C<key> and C<value>. The following code is equivalent:
306
307 foreach my $pair ( pairs @KVLIST ) {
308 my $key = $pair->key;
309 my $value = $pair->value;
310 ...
311 }
312
313=head2 unpairs
314
315 my @kvlist = unpairs @pairs
316
317I<Since version 1.42.>
318
319The inverse function to C<pairs>; this function takes a list of ARRAY
320references containing two elements each, and returns a flattened list of the
321two values from each of the pairs, in order. This is notionally equivalent to
322
323 my @kvlist = map { @{$_}[0,1] } @pairs
324
325except that it is implemented more efficiently internally. Specifically, for
326any input item it will extract exactly two values for the output list; using
327C<undef> if the input array references are short.
328
329Between C<pairs> and C<unpairs>, a higher-order list function can be used to
330operate on the pairs as single scalars; such as the following near-equivalents
331of the other C<pair*> higher-order functions:
332
333 @kvlist = unpairs grep { FUNC } pairs @kvlist
334 # Like pairgrep, but takes $_ instead of $a and $b
335
336 @kvlist = unpairs map { FUNC } pairs @kvlist
337 # Like pairmap, but takes $_ instead of $a and $b
338
339Note however that these versions will not behave as nicely in scalar context.
340
341Finally, this technique can be used to implement a sort on a keyvalue pair
342list; e.g.:
343
344 @kvlist = unpairs sort { $a->key cmp $b->key } pairs @kvlist
345
346=head2 pairkeys
347
348 my @keys = pairkeys @kvlist;
349
350I<Since version 1.29.>
351
352A convenient shortcut to operating on even-sized lists of pairs, this function
353returns a list of the the first values of each of the pairs in the given list.
354It is a more efficient version of
355
356 @keys = pairmap { $a } @kvlist
357
358=head2 pairvalues
359
360 my @values = pairvalues @kvlist;
361
362I<Since version 1.29.>
363
364A convenient shortcut to operating on even-sized lists of pairs, this function
365returns a list of the the second values of each of the pairs in the given list.
366It is a more efficient version of
367
368 @values = pairmap { $b } @kvlist
369
d81c2d6a
CBW
370=head2 pairgrep
371
372 my @kvlist = pairgrep { BLOCK } @kvlist;
8c167fd9 373
d81c2d6a 374 my $count = pairgrep { BLOCK } @kvlist;
2dc8d725 375
b823713c
CBW
376I<Since version 1.29.>
377
2dc8d725 378Similar to perl's C<grep> keyword, but interprets the given list as an
8c167fd9 379even-sized list of pairs. It invokes the C<BLOCK> multiple times, in scalar
2dc8d725 380context, with C<$a> and C<$b> set to successive pairs of values from the
8c167fd9 381C<@kvlist>.
2dc8d725 382
8c167fd9 383Returns an even-sized list of those pairs for which the C<BLOCK> returned true
2dc8d725 384in list context, or the count of the B<number of pairs> in scalar context.
8c167fd9
CBW
385(Note, therefore, in scalar context that it returns a number half the size of
386the count of items it would have returned in list context).
2dc8d725
CBW
387
388 @subset = pairgrep { $a =~ m/^[[:upper:]]+$/ } @kvlist
389
8c167fd9
CBW
390As with C<grep> aliasing C<$_> to list elements, C<pairgrep> aliases C<$a> and
391C<$b> to elements of the given list. Any modifications of it by the code block
392will be visible to the caller.
2dc8d725 393
d81c2d6a 394=head2 pairfirst
8c167fd9 395
d81c2d6a
CBW
396 my ( $key, $val ) = pairfirst { BLOCK } @kvlist;
397
398 my $found = pairfirst { BLOCK } @kvlist;
6a9ebaf3 399
b823713c
CBW
400I<Since version 1.30.>
401
d81c2d6a 402Similar to the L</first> function, but interprets the given list as an
8c167fd9 403even-sized list of pairs. It invokes the C<BLOCK> multiple times, in scalar
6a9ebaf3 404context, with C<$a> and C<$b> set to successive pairs of values from the
8c167fd9 405C<@kvlist>.
6a9ebaf3 406
8c167fd9 407Returns the first pair of values from the list for which the C<BLOCK> returned
6a9ebaf3
SH
408true in list context, or an empty list of no such pair was found. In scalar
409context it returns a simple boolean value, rather than either the key or the
410value found.
411
412 ( $key, $value ) = pairfirst { $a =~ m/^[[:upper:]]+$/ } @kvlist
413
8c167fd9
CBW
414As with C<grep> aliasing C<$_> to list elements, C<pairfirst> aliases C<$a> and
415C<$b> to elements of the given list. Any modifications of it by the code block
416will be visible to the caller.
417
d81c2d6a
CBW
418=head2 pairmap
419
420 my @list = pairmap { BLOCK } @kvlist;
6a9ebaf3 421
d81c2d6a 422 my $count = pairmap { BLOCK } @kvlist;
2dc8d725 423
b823713c
CBW
424I<Since version 1.29.>
425
2dc8d725 426Similar to perl's C<map> keyword, but interprets the given list as an
8c167fd9 427even-sized list of pairs. It invokes the C<BLOCK> multiple times, in list
2dc8d725 428context, with C<$a> and C<$b> set to successive pairs of values from the
8c167fd9 429C<@kvlist>.
2dc8d725 430
8c167fd9
CBW
431Returns the concatenation of all the values returned by the C<BLOCK> in list
432context, or the count of the number of items that would have been returned in
433scalar context.
2dc8d725
CBW
434
435 @result = pairmap { "The key $a has value $b" } @kvlist
436
8c167fd9
CBW
437As with C<map> aliasing C<$_> to list elements, C<pairmap> aliases C<$a> and
438C<$b> to elements of the given list. Any modifications of it by the code block
439will be visible to the caller.
2dc8d725 440
b823713c
CBW
441See L</KNOWN BUGS> for a known-bug with C<pairmap>, and a workaround.
442
6a9ebaf3 443=cut
f4a2945e 444
6a9ebaf3 445=head1 OTHER FUNCTIONS
f4a2945e 446
6a9ebaf3 447=cut
2ff28616 448
d81c2d6a
CBW
449=head2 shuffle
450
451 my @values = shuffle @values;
1bfb5477 452
8c167fd9 453Returns the values of the input in a random order
1bfb5477 454
c29e891d
GB
455 @cards = shuffle 0..51 # 0..51 in a random order
456
6a9ebaf3 457=cut
f4a2945e 458
9c3c560b
JH
459=head1 KNOWN BUGS
460
b823713c
CBW
461=head2 RT #95409
462
463L<https://rt.cpan.org/Ticket/Display.html?id=95409>
464
d81c2d6a 465If the block of code given to L</pairmap> contains lexical variables that are
b823713c
CBW
466captured by a returned closure, and the closure is executed after the block
467has been re-used for the next iteration, these lexicals will not see the
468correct values. For example:
469
470 my @subs = pairmap {
471 my $var = "$a is $b";
472 sub { print "$var\n" };
473 } one => 1, two => 2, three => 3;
474
475 $_->() for @subs;
476
477Will incorrectly print
478
479 three is 3
480 three is 3
481 three is 3
482
483This is due to the performance optimisation of using C<MULTICALL> for the code
484block, which means that fresh SVs do not get allocated for each call to the
485block. Instead, the same SV is re-assigned for each iteration, and all the
486closures will share the value seen on the final iteration.
487
488To work around this bug, surround the code with a second set of braces. This
489creates an inner block that defeats the C<MULTICALL> logic, and does get fresh
490SVs allocated each time:
491
492 my @subs = pairmap {
493 {
494 my $var = "$a is $b";
495 sub { print "$var\n"; }
496 }
497 } one => 1, two => 2, three => 3;
498
499This bug only affects closures that are generated by the block but used
500afterwards. Lexical variables that are only used during the lifetime of the
501block's execution will take their individual values for each invocation, as
502normal.
9c3c560b 503
f4a2945e
JH
504=head1 SUGGESTED ADDITIONS
505
506The following are additions that have been requested, but I have been reluctant
507to add due to them being very simple to implement in perl
508
f4a2945e
JH
509 # How many elements are true
510
511 sub true { scalar grep { $_ } @_ }
512
513 # How many elements are false
514
515 sub false { scalar grep { !$_ } @_ }
516
ddf53ba4
GB
517=head1 SEE ALSO
518
519L<Scalar::Util>, L<List::MoreUtils>
520
f4a2945e
JH
521=head1 COPYRIGHT
522
2ff28616 523Copyright (c) 1997-2007 Graham Barr <gbarr@pobox.com>. All rights reserved.
f4a2945e
JH
524This program is free software; you can redistribute it and/or
525modify it under the same terms as Perl itself.
526
6a9ebaf3
SH
527Recent additions and current maintenance by
528Paul Evans, <leonerd@leonerd.org.uk>.
529
f4a2945e 530=cut