I have an array with values 33, 32, 8, 100.
How can I find the maximum and minimum value in this array?
Do I need to include any special libraries?<
I think List::Util is what you are looking for.
You can use List::Util to do this easily, eg.
use List::Util qw(min max);
my @arr = (33, 32, 8, 100);
print min(@arr)," ", max(@arr), "\n";
You can use Statistics::Lite to compute min,max etc
List::Util's min
and max
are fine,
use List::Util qw( min max );
my $min = min @numbers;
my $max = max @numbers;
But List::MoreUtils's minmax
is more efficient when you need both the min and the max (because it does fewer comparisons).
use List::MoreUtils qw( minmax );
my ($min, $max) = minmax @numbers;
List::Util is part of core, but List::MoreUtils isn't.
Without modules:
#!/usr/bin/perl
use strict;
use warnings;
my @array = sort { $a <=> $b } qw(33 32 8 100);
print "min: $array[0]\n";
print "max: $array[-1]\n";
For numbers:
my ($min,$max) = (sort {$a <=> $b} @array)[0,-1];
For strings:
my ($min,$max) = (sort {$a cmp $b} @array)[0,-1];