Home Perl Programming Page 4 - Perl Lists: Utilizing List::Util

# Max()ing It Out - Perl

In this fifth part of our series on Lists, we will cover the List::Util module, which gives us seven handy-dandy subroutines with which to manipulate our lists. If we have time, we'll also cover multi-dimensional lists in more depth (we briefly covered them in an earlier article).

By: James Payne
Rating:  / 2
April 14, 2008

SEARCH DEV SHED

TOOLS YOU CAN USE

The Max function is used to return the maximum value in a list. It's that simple. Here it is at work:

#!/usr/bin/perl

use List::Util qw(max);

@Nums=(1,900,50,22);

\$High=max(@Nums);

print \$High;

This goes through our list @Nums, looks for the highest number, and places it in the \$high variable. Here is the obvious result:

900

As before, this bad boy can be used in conjunction with operators, statements, etc. Here it is with an if...else:

#!/usr/bin/perl

use List::Util qw(max);

@Nums=(1,900,50,22);

\$high=max(@Nums);

if(\$high > 25) {print "The number \$high is greater than 25!"}

else {print "The value \$high is less than 25!"};

This will print out:

The value 900 is greater than 25!

We can also perform calculations off of our subroutine. Here is a simple addition:

#!/usr/bin/perl

use List::Util qw(max);

@Nums=(1,900,50,22);

\$high=max(@Nums) + 1;

print \$high;

Giving us:

901

Here is a final example showcasing how you can compare the highest values of two lists:

#!/usr/bin/perl

use List::Util qw(max);

@Nums=(1,900,50,22);

@Nums2=(90..898);

\$High=max(@Nums);

\$Less=max(@Nums2);

if(\$High > \$Less) {\$Less=\$High};

print \$High . "\n";

print \$Less;

This code creates two arrays. We fill one with some values and we use a sequential operator to fill the other. Next, we use max to find the maximum value in each and store them in their respective variables. Finally, we use an if statement to determine whether \$High is greater than \$Less. If so, then the value in \$Less is given the same value as the variable \$High. We then print out the result of both variables:

900

900

You will note that we only used numbers in the previous example. In order to find the highest string value, we use our good buddy and max(List)'s cousin, maxstr(List).

 >>> More Perl Programming Articles          >>> More By James Payne