cpan beginner

How to use List::Util sum function in Perl?

Question

How to use List::Util sum function in Perl?

How to Use the sum Function from List::Util in Perl

The sum function from the List::Util module is a convenient and efficient way to add up a list of numbers in Perl. Introduced in Perl 5.8.8 and enhanced in later versions, List::Util is a core module that provides essential list utility functions including sum.

Using sum is much cleaner and less error-prone compared to summing elements manually in a loop. It automatically returns the total of all elements passed to it, or undef if the list is empty.

Key concepts:

  • List::Util is a core Perl module, so no extra installation is required.
  • sum takes one or more numbers (scalars) or a list of numbers (array) as arguments.
  • The return value is the numeric sum of all elements.
  • If the list is empty, sum returns undef, so be careful when printing or using the result directly.
  • Perl's flexibility with context (scalar, list) applies, but sum is always scalar context—it returns a single number.

Example usage


use strict;
use warnings;
use List::Util qw(sum);

# Define an array of numbers
my @numbers = (10, 20, 30, 40);

# Use sum to add them up
my $total = sum(@numbers);

if (defined $total) {
    print "The sum of the numbers is: $total\n";
} else {
    print "The list is empty, no sum available.\n";
}

# Summing an empty list returns undef
my @empty = ();
my $no_sum = sum(@empty);
print "Sum of empty list: ", defined $no_sum ? $no_sum : 'undef', "\n";

Explanation

Here’s what happens in the example above:

  • We use List::Util qw(sum) to import only the sum function for clean namespace management.
  • sum(@numbers) calculates the total of all elements—10 + 20 + 30 + 40 = 100.
  • If the array is empty, sum returns undef, so we check definedness before printing to avoid warnings.

Common pitfalls to avoid

  • Passing a list that contains non-numeric values may cause warnings or unexpected results. Always ensure your list contains numbers.
  • Remember sum returns undef on an empty list rather than zero. This often surprises beginners.
  • Use defined to check the return value before using it in numeric operations or printing.
  • Don’t forget to import sum from List::Util. Without import, you must call List::Util::sum(...) explicitly.

Conclusion

The sum function from List::Util is the idiomatic way to sum an array or list of numbers in Perl. Its clean syntax, core availability, and correctness make it better than manual loops or reducing with addition. Just remember to handle empty lists safely for robust scripts.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 16ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
The sum of the numbers is: 100
Sum of empty list: undef
STDERR
(empty)

Was this helpful?

Related Questions