Name

reduce

Synopsis

reduce { BLOCK } @list
                  

Literally “reduces” @ list by calling BLOCK until there are no more items to operate on in @ list. reduce sets $a and $b for each operation in BLOCK and returns the reduced list as a scalar. If @ list is 0, BLOCK is not executed, and $ list [0] is returned. If @list is empty, then reduce returns undef.

You can sum and concatenate a list using reduce like so:

my $sum_of_list = reduce { $a + $b } @ll; # sum
my $concat_list = reduce { $a . $b } @ll; # concat

Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.