This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Integrate CPAN release of version.pm 0.9905
[perl5.git] / cpan / Scalar-List-Utils / lib / List / Util.pm
CommitLineData
f4a2945e
JH
1# List::Util.pm
2#
2ff28616 3# Copyright (c) 1997-2009 Graham Barr <gbarr@pobox.com>. All rights reserved.
f4a2945e
JH
4# This program is free software; you can redistribute it and/or
5# modify it under the same terms as Perl itself.
2ff28616 6#
e99e4210 7# Maintained since 2013 by Paul Evans <leonerd@leonerd.org.uk>
f4a2945e
JH
8
9package List::Util;
10
82f35e8b 11use strict;
f4a2945e
JH
12require Exporter;
13
3630f57e 14our @ISA = qw(Exporter);
52102bb4 15our @EXPORT_OK = qw(
98eca5fa 16 all any first min max minstr maxstr none notall product reduce sum sum0 shuffle
52102bb4
SH
17 pairmap pairgrep pairfirst pairs pairkeys pairvalues
18);
98eca5fa 19our $VERSION = "1.35";
3630f57e 20our $XS_VERSION = $VERSION;
60f3865b 21$VERSION = eval $VERSION;
f4a2945e 22
3630f57e
CBW
23require XSLoader;
24XSLoader::load('List::Util', $XS_VERSION);
09c2a9b8 25
52102bb4
SH
26sub import
27{
28 my $pkg = caller;
29
30 # (RT88848) Touch the caller's $a and $b, to avoid the warning of
31 # Name "main::a" used only once: possible typo" warning
32 no strict 'refs';
33 ${"${pkg}::a"} = ${"${pkg}::a"};
34 ${"${pkg}::b"} = ${"${pkg}::b"};
35
36 goto &Exporter::import;
37}
38
f4a2945e
JH
391;
40
41__END__
42
43=head1 NAME
44
45List::Util - A selection of general-utility list subroutines
46
47=head1 SYNOPSIS
48
c29e891d 49 use List::Util qw(first max maxstr min minstr reduce shuffle sum);
f4a2945e
JH
50
51=head1 DESCRIPTION
52
53C<List::Util> contains a selection of subroutines that people have
54expressed would be nice to have in the perl core, but the usage would
55not really be high enough to warrant the use of a keyword, and the size
56so small such that being individual extensions would be wasteful.
57
6a9ebaf3 58By default C<List::Util> does not export any subroutines.
f4a2945e 59
6a9ebaf3
SH
60=cut
61
62=head1 LIST-REDUCTION FUNCTIONS
63
64The following set of functions all reduce a list down to a single value.
65
66=cut
67
68=head2 reduce BLOCK LIST
69
70Reduces LIST by calling BLOCK, in a scalar context, multiple times,
71setting C<$a> and C<$b> each time. The first call will be with C<$a>
72and C<$b> set to the first two elements of the list, subsequent
73calls will be done by setting C<$a> to the result of the previous
74call and C<$b> to the next element in the list.
75
76Returns the result of the last call to BLOCK. If LIST is empty then
77C<undef> is returned. If LIST only contains one element then that
78element is returned and BLOCK is not executed.
f4a2945e 79
e99e4210
SH
80The following examples all demonstrate how C<reduce> could be used to
81implement the other list-reduction functions in this module. (They are
82not in fact implemented like this, but instead in a more efficient
83manner in individual C functions).
84
85 $foo = reduce { defined($a) ? $a :
86 $code->(local $_ = $b) ? $b :
87 undef } undef, @list # first
88
89 $foo = reduce { $a > $b ? $a : $b } 1..10 # max
90 $foo = reduce { $a gt $b ? $a : $b } 'A'..'Z' # maxstr
6a9ebaf3
SH
91 $foo = reduce { $a < $b ? $a : $b } 1..10 # min
92 $foo = reduce { $a lt $b ? $a : $b } 'aa'..'zz' # minstr
93 $foo = reduce { $a + $b } 1 .. 10 # sum
94 $foo = reduce { $a . $b } @bar # concat
95
e99e4210
SH
96 $foo = reduce { $a || $code->(local $_ = $b) } 0, @bar # any
97 $foo = reduce { $a && $code->(local $_ = $b) } 1, @bar # all
98 $foo = reduce { $a && !$code->(local $_ = $b) } 1, @bar # none
99 $foo = reduce { $a || !$code->(local $_ = $b) } 0, @bar # notall
100 # Note that these implementations do not fully short-circuit
101
6a9ebaf3
SH
102If your algorithm requires that C<reduce> produce an identity value, then
103make sure that you always pass that identity value as the first argument to prevent
104C<undef> being returned
105
106 $foo = reduce { $a + $b } 0, @values; # sum with 0 identity value
107
108The remaining list-reduction functions are all specialisations of this
109generic idea.
110
52102bb4
SH
111=head2 any BLOCK LIST
112
113Similar to C<grep> in that it evaluates BLOCK setting C<$_> to each element
114of LIST in turn. C<any> returns true if any element makes the BLOCK return a
115true value. If BLOCK never returns true or LIST was empty then it returns
116false.
117
118Many cases of using C<grep> in a conditional can be written using C<any>
119instead, as it can short-circuit after the first true result.
120
121 if( any { length > 10 } @strings ) {
122 # at least one string has more than 10 characters
123 }
124
125=head2 all BLOCK LIST
126
127Similar to C<any>, except that it requires all elements of the LIST to make
128the BLOCK return true. If any element returns false, then it returns true. If
129the BLOCK never returns false or the LIST was empty then it returns true.
130
131=head2 none BLOCK LIST
132
133=head2 notall BLOCK LIST
134
135Similar to C<any> and C<all>, but with the return sense inverted. C<none>
136returns true if no value in the LIST causes the BLOCK to return true, and
137C<notall> returns true if not all of the values do.
138
6a9ebaf3 139=head2 first BLOCK LIST
f4a2945e
JH
140
141Similar to C<grep> in that it evaluates BLOCK setting C<$_> to each element
142of LIST in turn. C<first> returns the first element where the result from
143BLOCK is a true value. If BLOCK never returns true or LIST was empty then
144C<undef> is returned.
145
146 $foo = first { defined($_) } @list # first defined value in @list
147 $foo = first { $_ > $value } @list # first value in @list which
148 # is greater than $value
c29e891d 149
6a9ebaf3 150=head2 max LIST
f4a2945e
JH
151
152Returns the entry in the list with the highest numerical value. If the
153list is empty then C<undef> is returned.
154
155 $foo = max 1..10 # 10
156 $foo = max 3,9,12 # 12
157 $foo = max @bar, @baz # whatever
158
6a9ebaf3 159=head2 maxstr LIST
f4a2945e
JH
160
161Similar to C<max>, but treats all the entries in the list as strings
162and returns the highest string as defined by the C<gt> operator.
163If the list is empty then C<undef> is returned.
c29e891d
GB
164
165 $foo = maxstr 'A'..'Z' # 'Z'
f4a2945e
JH
166 $foo = maxstr "hello","world" # "world"
167 $foo = maxstr @bar, @baz # whatever
168
6a9ebaf3 169=head2 min LIST
f4a2945e
JH
170
171Similar to C<max> but returns the entry in the list with the lowest
172numerical value. If the list is empty then C<undef> is returned.
173
174 $foo = min 1..10 # 1
175 $foo = min 3,9,12 # 3
176 $foo = min @bar, @baz # whatever
177
6a9ebaf3 178=head2 minstr LIST
f4a2945e
JH
179
180Similar to C<min>, but treats all the entries in the list as strings
181and returns the lowest string as defined by the C<lt> operator.
182If the list is empty then C<undef> is returned.
183
c29e891d
GB
184 $foo = minstr 'A'..'Z' # 'A'
185 $foo = minstr "hello","world" # "hello"
186 $foo = minstr @bar, @baz # whatever
f4a2945e 187
98eca5fa
SH
188=head2 product LIST
189
190Returns the product of all the elements in LIST. If LIST is empty then C<1> is
191returned.
192
193 $foo = product 1..10 # 3628800
194 $foo = product 3,9,12 # 324
195
6a9ebaf3
SH
196=head2 sum LIST
197
198Returns the sum of all the elements in LIST. If LIST is empty then
199C<undef> is returned.
200
201 $foo = sum 1..10 # 55
202 $foo = sum 3,9,12 # 24
203 $foo = sum @bar, @baz # whatever
204
6a9ebaf3
SH
205=head2 sum0 LIST
206
207Similar to C<sum>, except this returns 0 when given an empty list, rather
208than C<undef>.
209
210=cut
211
212=head1 KEY/VALUE PAIR LIST FUNCTIONS
213
214The following set of functions, all inspired by L<List::Pairwise>, consume
215an even-sized list of pairs. The pairs may be key/value associations from a
216hash, or just a list of values. The functions will all preserve the original
217ordering of the pairs, and will not be confused by multiple pairs having the
218same "key" value - nor even do they require that the first of each pair be a
219plain string.
220
221=cut
222
223=head2 pairgrep BLOCK KVLIST
2dc8d725
CBW
224
225Similar to perl's C<grep> keyword, but interprets the given list as an
226even-sized list of pairs. It invokes the BLOCK multiple times, in scalar
227context, with C<$a> and C<$b> set to successive pairs of values from the
228KVLIST.
229
230Returns an even-sized list of those pairs for which the BLOCK returned true
231in list context, or the count of the B<number of pairs> in scalar context.
232(Note, therefore, in scalar context that it returns a number half the size
233of the count of items it would have returned in list context).
234
235 @subset = pairgrep { $a =~ m/^[[:upper:]]+$/ } @kvlist
236
237Similar to C<grep>, C<pairgrep> aliases C<$a> and C<$b> to elements of the
238given list. Any modifications of it by the code block will be visible to
239the caller.
240
6a9ebaf3
SH
241=head2 pairfirst BLOCK KVLIST
242
243Similar to the C<first> function, but interprets the given list as an
244even-sized list of pairs. It invokes the BLOCK multiple times, in scalar
245context, with C<$a> and C<$b> set to successive pairs of values from the
246KVLIST.
247
248Returns the first pair of values from the list for which the BLOCK returned
249true in list context, or an empty list of no such pair was found. In scalar
250context it returns a simple boolean value, rather than either the key or the
251value found.
252
253 ( $key, $value ) = pairfirst { $a =~ m/^[[:upper:]]+$/ } @kvlist
254
255Similar to C<grep>, C<pairfirst> aliases C<$a> and C<$b> to elements of the
256given list. Any modifications of it by the code block will be visible to
257the caller.
258
259=head2 pairmap BLOCK KVLIST
2dc8d725
CBW
260
261Similar to perl's C<map> keyword, but interprets the given list as an
262even-sized list of pairs. It invokes the BLOCK multiple times, in list
263context, with C<$a> and C<$b> set to successive pairs of values from the
264KVLIST.
265
266Returns the concatenation of all the values returned by the BLOCK in list
267context, or the count of the number of items that would have been returned
268in scalar context.
269
270 @result = pairmap { "The key $a has value $b" } @kvlist
271
272Similar to C<map>, C<pairmap> aliases C<$a> and C<$b> to elements of the
273given list. Any modifications of it by the code block will be visible to
274the caller.
275
6a9ebaf3 276=head2 pairs KVLIST
2dc8d725
CBW
277
278A convenient shortcut to operating on even-sized lists of pairs, this
279function returns a list of ARRAY references, each containing two items from
280the given list. It is a more efficient version of
281
282 pairmap { [ $a, $b ] } KVLIST
283
284It is most convenient to use in a C<foreach> loop, for example:
285
286 foreach ( pairs @KVLIST ) {
287 my ( $key, $value ) = @$_;
288 ...
289 }
290
6a9ebaf3 291=head2 pairkeys KVLIST
2dc8d725
CBW
292
293A convenient shortcut to operating on even-sized lists of pairs, this
294function returns a list of the the first values of each of the pairs in
295the given list. It is a more efficient version of
296
297 pairmap { $a } KVLIST
298
6a9ebaf3 299=head2 pairvalues KVLIST
2dc8d725
CBW
300
301A convenient shortcut to operating on even-sized lists of pairs, this
302function returns a list of the the second values of each of the pairs in
303the given list. It is a more efficient version of
304
305 pairmap { $b } KVLIST
306
6a9ebaf3 307=cut
f4a2945e 308
6a9ebaf3 309=head1 OTHER FUNCTIONS
f4a2945e 310
6a9ebaf3 311=cut
2ff28616 312
6a9ebaf3 313=head2 shuffle LIST
1bfb5477
GB
314
315Returns the elements of LIST in a random order
316
c29e891d
GB
317 @cards = shuffle 0..51 # 0..51 in a random order
318
6a9ebaf3 319=cut
f4a2945e 320
9c3c560b
JH
321=head1 KNOWN BUGS
322
323With perl versions prior to 5.005 there are some cases where reduce
324will return an incorrect result. This will show up as test 7 of
325reduce.t failing.
326
f4a2945e
JH
327=head1 SUGGESTED ADDITIONS
328
329The following are additions that have been requested, but I have been reluctant
330to add due to them being very simple to implement in perl
331
f4a2945e
JH
332 # How many elements are true
333
334 sub true { scalar grep { $_ } @_ }
335
336 # How many elements are false
337
338 sub false { scalar grep { !$_ } @_ }
339
ddf53ba4
GB
340=head1 SEE ALSO
341
342L<Scalar::Util>, L<List::MoreUtils>
343
f4a2945e
JH
344=head1 COPYRIGHT
345
2ff28616 346Copyright (c) 1997-2007 Graham Barr <gbarr@pobox.com>. All rights reserved.
f4a2945e
JH
347This program is free software; you can redistribute it and/or
348modify it under the same terms as Perl itself.
349
6a9ebaf3
SH
350Recent additions and current maintenance by
351Paul Evans, <leonerd@leonerd.org.uk>.
352
f4a2945e 353=cut