How to find the maximum number in Perl array

Task. In Perl, the program has an array @arr (the first three letters from the word "array"). Need to find the maximum number that is this array.

The best way to solve this problem is to use the function max from the library List::Util. Library List::Util comes with Perl, so if you have Perl, this library is available to additionally install nothing.

Here is an example program that finds and displays the maximum number from the array which contains the numbers:

▶ Run

use List::Util qw(max);

my @arr = (1, 2, -100, 8, 0);

print max(@arr);

The program will display the number 8. (To execute the code in the browser ).

When you connect a library we have indicated that we will use the function max: use List::Util qw(max);. If you just connect the library use List::Util;, the program will issue an error Undefined subroutine &main::max called at line 7..

In the array has no elements

If the array has no elements, then max will return undef. Here is the sample program which takes into account the following case:

▶ Run

use List::Util qw(max);

my @arr;

my $max = max(@arr);

if (defined $max) {
    print $max;
} else {
    print "Empty array";

In this program we store the result of the function max in the variable if the result is not undef, we deduce this result, if undef, we deduce the text on the screen.

Here we check the result of the function max, but it would be possible to know the number of elements in the array and if the number of items is 0, then perform what you need to do in case of an empty array.

Work in case the array has string

When working with the function max from the library List::Util there is one subtlety. Actually max return the maximum number from the array, and the element whose view number is the maximum.

Here is an example. The result max(-100, 'ABC', -4) will line 'ABC'. This happens due to the fact that the numeric value of the string 'ABC' is zero, zero is the largest value in this array, so will result is the element with the highest numeric value. In this example, the string 'ABC'.

Another example. The result max(1, 7, '10W') will line '10W'.

Official documentation

Here's a snippet of the output perldoc List::Util  about the function max:

        my $num = max @list;

    Returns the entry in the list with the highest numerical value. If the
    list is empty then "undef" is returned.

        $foo = max 1..10                # 10
        $foo = max 3,9,12               # 12
        $foo = max @bar, @baz           # whatever

Other articles