List::Util#

📦 std

The standard library of list reductions and scanners.

List::Util is the first stop when you need to collapse a list to a single answer (sum, max, product, reduce), find or test elements by predicate (first, any, all, none, notall), strip duplicates (uniq, uniqnum, uniqint, uniqstr), or reshape an even-sized key/value list (pairs, pairkeys, pairmap, pairgrep). It also covers slicing (head, tail), randomisation (shuffle, sample), and lockstep iteration over multiple arrays (zip, mesh, and their _shortest / _longest variants).

The block-taking reductions - reduce, reductions, pairmap, pairgrep, pairfirst - expose the current pair or accumulator through $a and $b. The per-element scanners - first, any, all, none, notall - expose the current element through $_.

Sub::Util (subname, set_subname, set_prototype) ships with the same distribution and becomes available once List::Util is loaded; import it from Sub::Util as usual.

This is List::Util from Scalar-List-Utils 1.70; List/Util.pm is upstream’s. Nothing is exported by default.

Synopsis#

use List::Util qw(sum max first any reduce uniq pairs pairmap head shuffle zip);

my @n = (3, 9, 4, 1, 9);
print sum(@n), ' ', max(@n), "\n";                    # 26 9
print first { $_ > 3 } @n;                            # 9
print((any { $_ == 4 } @n) ? "has 4\n" : "no 4\n");   # has 4
print reduce { $a * $b } 1 .. 5;                      # 120
print join(',', uniq @n), "\n";                       # 3,9,4,1

my %age = (alice => 30, bob => 25);
for my $p (sort { $a->key cmp $b->key } pairs %age) {
    printf "%s is %d\n", $p->key, $p->value;          # alice is 30, bob is 25
}
print join(',', pairmap { "$a=$b" } %age), "\n";      # alice=30,bob=25 (hash order)
print join(',', head 2, @n), "\n";                    # 3,9
print join(' ', map { "[@$_]" } zip [1, 2], ['a', 'b']), "\n";   # [1 a] [2 b]
my @deck = shuffle 1 .. 52;

sum, product, min and max of a long list of plain integers (65536 elements and more) run on several cores; the answer is the one the single-core loop gives, the same element for min and max. --no-parallel turns that off.

Differences from upstream#

Each where perl 5.44 with ListUtil.xs fails (t/81-xs-native/List-Util/151-or-better.t):

  • unpairs 42 croaks “Not a reference”; perl5 crashes.

  • unpairs takes an array reference held in a variable that once held a string (my $x = "abc"; $x = [1, 2]); perl5 refuses it.

  • mesh reads a hole in an input array (my @h; $h[2] = 5) as undef; perl5 crashes.

Modules#

Functions#

Reductions#

sum#

Add up every value in the list and return the numerical total.

sum0#

Add up every value in the list, returning 0 for an empty list.

min#

Return the numerically smallest value in the list.

max#

Return the numerically largest value in the list.

product#

Multiply every value in the list and return the numerical product.

minstr#

Return the lexically smallest value in the list.

maxstr#

Return the lexically largest value in the list.

reduce#

Collapse a list to a single value by repeated pairwise combination.

reductions#

Like reduce, but also return every intermediate accumulator value.

Scanners#

first#

Return the first list element for which a block returns true.

any#

True if the block returns true for at least one element.

all#

True if the block returns true for every element (including empty list).

none#

True if the block returns true for no element (including empty list).

notall#

True if the block returns false for at least one element.

Pair handling#

pairs#

Group an even-sized list into key/value pair objects.

unpairs#

Flatten a list of two-element arrayrefs into a key/value list.

pairkeys#

Extract just the keys from an even-sized key/value list.

pairvalues#

Extract just the values from an even-sized key/value list.

pairmap#

Run a block for each pair and concatenate the results.

pairgrep#

Keep the pairs for which a block returns true.

pairfirst#

Return the first pair for which a block returns true.

Selection#

tail#

Return the last $size elements of a list.

uniq#

Remove subsequent duplicates by string equality, preserving order.

uniqstr#

Remove subsequent duplicates by string equality, treating undef as the empty string.

uniqnum#

Remove subsequent duplicates by numerical equality, preserving order.

uniqint#

Remove subsequent duplicates by integer equality, preserving order.

Misc#

shuffle#

Return the input list in a uniformly random order.

sample#

Pick $count distinct elements from the list at random.

mesh#

Interleave multiple arrays, padding shorter ones with undef.

mesh_longest#

The same as mesh, by the name that says what it does with lists of different lengths: the elements run to the longest input, the shorter ones padded with undef.

mesh_shortest#

Interleave multiple arrays, stopping at the shortest.

zip#

Walk multiple arrays in lockstep, returning one arrayref per row.

zip_longest#

The same as zip, by the name that says what it does with lists of different lengths: rows run to the longest input, the shorter ones padded with undef.

zip_shortest#

Walk multiple arrays in lockstep, stopping at the shortest.