Perlish – List Utilities

Posted by Joe Topjian on April 27, 2011 under Development | Be the First to Comment

Introduction

There are two CPAN modules that provide some nice utilities for working with and manipulating lists: List::Util and List::MoreUtils. This article quickly covers a few of these utilities that I have found useful.

Table of Contents

List::Util

List::Util provides a handful of utilities. Some of these are:

List::Util::first

List::Util::first will return the first element in a list that matches a given criteria:

my @list = qw(1 2 3 4 5 6);
my $first = first { $_ > 4 } @list;  # returns 5

List::Util::max

List::Util::max returns the maximum number from a list:

my @list = qw(1 2 3 4 5 6);
my $ = max @list;  # returns 6

List::Util::shuffle

List::Util::shuffle randomizes a list:

my @list = shuffle qw(1 2 3 4 5 6);
say $list[0] # prints random number between 1 - 6

List::MoreUtils

List::MoreUtils, as the name implies, provides some more list utilities.

List::MoreUtils::any

List::MoreUtils::any returns true if any element in the list fits the given criteria:

say "true" if (any { $_ > 5 } qw(1 2 3 4 5 6));

List::MoreUtils::all

List::MoreUtils::all returns true if all elements in the list fit the given criteria:

say "true" if (all {$_ > 0) qw(1 2 3 4 5 6));

List::MoreUtils::uniq

List::MoreUtils::uniq can provide two functions:

  • In list context, it will return a list of only unique elements
  • In scalar context, it will return the number of unique elements
my @list = qw(1 1 2 3 4 4 4 5 6 6);
my @uniqs = uniq @list;
print Dumper @uniqs; # returns 1 2 3 4 5 6
my $unique_count; = uniq @list;
say $unique_count; # prints 6

Conclusion

As you can see, these two modules provide some nice convenience functions. There are many more to learn, so check out the CPAN page for each.

Add A Comment