← Back to Perl Course | Chapter 8: Modules | Lesson 2 of 7

List::Util

List::Util gives you fast helpers such as sum, max, first and reduce for working with lists.

In this page:

  1. List::Util

List::Util

List::Util is a core module whose functions are written in C and imported by name. sum, min, max and product reduce a list to one number, first returns the first element for which a block is true, and reduce combines a list with a block using $a and $b. uniq returns the elements without duplicates, and shuffle mixes them in random order.

Note: sum and max return undef for an empty list, so guard against that when the list may be empty.

Example: List::Util

perl
use strict;
use warnings;
use List::Util qw(sum min max product first reduce uniq);

my @nums = (4, 8, 15, 16, 23, 42);
print "sum: ", sum(@nums), "\n";
print "min: ", min(@nums), " max: ", max(@nums), "\n";
print "product of 1..5: ", product(1 .. 5), "\n";
my $big = first { $_ > 10 } @nums;
print "first over 10: $big\n";
my $longest = reduce { length($a) >= length($b) ? $a : $b } qw(pear banana fig apple);
print "longest word: $longest\n";
print "unique: ", join(" ", uniq(1, 1, 2, 3, 3, 3)), "\n";
my $empty = sum();
print "sum of nothing: ", defined $empty ? $empty : "undef", "\n";

# Output:
# sum: 108
# min: 4 max: 42
# product of 1..5: 120
# first over 10: 15
# longest word: banana
# unique: 1 2 3
# sum of nothing: undef
Common Mistakes
  1. Forgetting to import the function names
  2. Using $_ instead of $a and $b inside reduce
  3. Expecting first to return the index of the element rather than the element itself
Chapter Summary
  • sum, min, max and product combine numbers
  • first finds the first matching element
  • reduce folds a list using $a and $b
  • uniq removes duplicates
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.