How to find the minimum number in a Perl array

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

The best way to solve this problem is to use the function min 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 minimum number from the array which contains the numbers:

▶ Run

use List::Util qw(min);

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

print min(@arr);

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

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

In the array has no elements

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

▶ Run

use List::Util qw(min);

my @arr;

my $min = min(@arr);

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

In this program we store the result of the function min 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 min, 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 min from the library List::Util there is one subtlety. Actually min does not return the minimum number from the array, and the element whose view number is minimal.

Here is an example. The result min(12, 'ABC', 44) will line 'ABC'. This happens due to the fact that the numeric value of the string 'ABC' is zero, zero is the smallest value in this array. The result min is the element whose numeric value is minimal. In this example, the string 'ABC'.

Another example. The result min(10, 7, '4H') will line '4H'.

Official documentation

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

        my $num = min @list;

    Similar to "max" but returns the entry in the list with the lowest
    numerical value. If the list is empty then "undef" is returned.

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

Other articles