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