How to find maximum and minimum value in an array of integers in Perl?

后端 未结 12 2073
花落未央
花落未央 2020-12-14 18:43

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?<

12条回答
  •  -上瘾入骨i
    2020-12-14 19:25

    Ofcourse, if you want both the maxium and minimum value of a list at the same time, it is more efficient to fetch both at once; it only has to perform 3 order comparisons per 2 items of data, rather than 4. This may matter if the data sets are big enough.

    List::Util doesn't provide a minmax function but List::MoreUtils does.

    use strict;
    use warnings;
    use feature qw( say );
    
    use List::MoreUtils qw( minmax );
    
    my ( $min, $max ) = minmax @data;
    
    say $min;
    say $max;
    

提交回复
热议问题