Book HomeJava and XSLTSearch this book

8.140. List::Util

A collection of list-related subroutines. As of Perl 5.8, List::Util is included with the Perl source kit.

You can get the first item of a list (that matches the condition in BLOCK) like so:

#!/usr/local/bin/perl -w
use List::Util qw(first);

my @ll = qw(one two three);

my $fir = first { defined($_) } @ll;
print "$fir\n"; # Prints 'one'

List::Util implements (but does not export) the following methods.

first

first { BLOCK } @list

Evaluates a block of Perl code and sets $_ to each element of the list in turn. If BLOCK is true, first returns the first element. If BLOCK never returns true, or @list has no items, then first returns undef. Note that first doesn't necessarily return the first item in a list. Consider the following:

my @ll = qw(1 2 3);
my $fir = first { $_ > 1 } @ll;
print "$fir\n"; # Prints '2', since as 2 is the first item
                # in BLOCK that's > 1
max

max @list

Returns the entry in the list with the highest numerical value. If the list is empty, max returns undef:

my @ll = qw(100 294 2 4 95 73);
my $max_num = max @ll; 
print "$max_num\n"; # Prints '294'
maxstr

maxstr @list

Similar to max, except that maxstr treats all list items as strings. maxstr will return the "highest string" as determined by the gt operator. As always, if list is empty, maxstr returns undef.

my @ll = qw(1 3 5 nate Person pizza man carl_everett dinosaur);
my $max_s = maxstr(@ll);
print "$max_s\n"; # Prints 'pizza'
min

min @list

Returns the lowest numerical value. If the list is empty, min returns undef.

minstr

minstr @list

Treats all list items as strings, but returns the "lowest string" as determined by the lt operator. If the list is empty, minstr returns undef.

reduce

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
shuffle

shuffle @LIST

Returns list items in random order.

sum

sum @LIST

Returns the sum of all items in the list. Note that sum deals only with numerical list items and will ignore any other list items. For example:

my @ll = qw(1 3 5 nate Person pizza man carl_everett dinosaur 6.54);
my $sum_of_list = sum(@ll);
print "$sum_of_list\n"; # Prints '15.54'


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.