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

后端 未结 12 2030
花落未央
花落未央 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条回答
  • 2020-12-14 19:35

    I think List::Util is what you are looking for.

    0 讨论(0)
  • 2020-12-14 19:36

    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";
    
    0 讨论(0)
  • 2020-12-14 19:36

    You can use Statistics::Lite to compute min,max etc

    0 讨论(0)
  • 2020-12-14 19:40

    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.

    0 讨论(0)
  • 2020-12-14 19:40

    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";
    
    0 讨论(0)
  • 2020-12-14 19:41

    For numbers:

        my ($min,$max) = (sort {$a <=> $b} @array)[0,-1];
    

    For strings:

        my ($min,$max) = (sort {$a cmp $b} @array)[0,-1];
    
    0 讨论(0)
提交回复
热议问题