The 2001 Perl Advent Calendar
[about] | [archives] | [contact] | [home]

On the 8th day of Advent my True Language brought to me..

Just as a Scalar::Util is useful for dealing with Scalars, List::Util allows you to do a whole bunch of useful things with lists. Of course, all the things in this module are possible to implement fairly easily without the module, but by using the module we we instantly get clarity of code, and much less chance of introducing subtle bugs.

List::Util comes with a set of standard useful things, you can shuffle lists, add the lists up, find the largest or smallest value.

More fun, and harder to write succinctly without the module are the first and reduce operators. first is really a godsend - it simply returns the first element of the list the condition is true for. This is actually quite hard to write in normal code in a way that it's clear what you're doing (normally you have to use a while loop and remember the index you were at) whereas List::Util lets you write it in a functional style.

The reduce method gives us a structure for running over the list keeping some sort of running value, and can be used to form a basis for any of the other operations. In conjunction with grep and map this operation can be used to do incredibly complex list operations in mere lines rather than pages of code.