[ Perl tips index ]
[ Subscribe to Perl tips ]

The List::Util module comes standard with Perl for versions 5.8.0 and greater and can be found on CPAN for other versions. It provides a number of general utility subroutines to make your life much easier.


Have you ever wanted a function to let you know if something you have is a member of a given list? Have you ever wanted a function to give you the first value which satisfies a given criteria (the first full moon in a list of dates, the first number greater than 100, the first true value)?

If so, you'll probably appreciate the first function:

        use List::Util qw(first);
        my $first_true    = first { $_ } @list;
        my $first_defined = first { defined($_) } @list;
        my $first_big     = first { $_ > 100 } @list;

first can be used instead of many for loops and grep.


If you're writing a card game you might want to be able to shuffle your array of cards. The shuffle function provided in List::Util provides a good shuffle with a fair amount of randomness.

        use List::Util qw(shuffle);
        my @shuffled = shuffle @cards;

max/maxstr, min/minstr

To determine the maximum value in a list you can use max for numbers and maxstr for strings. min and minstr do the same for the minimum value.

        use List::Util qw(max maxstr min minstr);
        my $max_num = max @numbers;
        my $max_str = maxstr @strings;
        my $min_num = min @numbers;
        my $min_str = minstr @strings;


To add all the values in a list you could write it yourself:

        my $sum;
        $sum += $_ for @list;

or you could use List::Util's sum method:

        use List::Util qw(sum);
        my $sum = sum @list;
        # or
        my $bigger_sum = sum @list1, @list2, @list3;


Some of the above functions are provided by using the reduce function. reduce calls its block multiple times to reduce the list into a single value. The first time the block is called the special variables $a and $b are set to the first two elements of the list. Each subsequent call sets $a to the result of the previous call and $b to the next value in the list.

Thus sum could be replaced with:

        my $sum = reduce { $a + $b } @list;

and max could be replaced with:

        my $max_num = reduce { $a > $b ? $a : $b } 1..10;

Whenever you need to do something to all of the elements of a list and get a single result you might want to think about using reduce.

[ Perl tips index ]
[ Subscribe to Perl tips ]

This Perl tip and associated text is copyright Perl Training Australia. You may freely distribute this text so long as it is distributed in full with this Copyright noticed attached.

If you have any questions please don't hesitate to contact us:

Phone: 03 9354 6001 (Australia)
International: +61 3 9354 6001

Valid XHTML 1.0 Valid CSS