Why does my Perl max () function always return the first element of an array?

I'm relatively new to Perl, and I don't want to use the List :: Util function maxto find the maximum value of a given array.

When I test the code below, it just returns the first value of the array, not the maximum.

sub max
{
    my @array = shift;
    my $cur = $array[0];
    foreach $i (@array)
    {
        if($i > $cur)
        {
            $cur = $i;
        }
        else
        {
            $cur = $cur;
        }
    }
    return $cur;
   }
+5
source share
3 answers

Replace

my @array = shift;

from

my @array = @_;

@_is an array containing all the arguments to the function. shiftonly grabs the first argument of the function and removes it from @_. Change this code and it will work correctly!

+8
source

Why don't you want to use something that works?

. , , , . :

 print "array is [@array]\n";

:

 use Data::Dumper;
 print Dumper( \@array );

, @array , .

, , Learning Perl.

+2

You can write a function as:

#!/usr/bin/perl

use strict; use warnings;

print max(@ARGV);

sub max {
    my $max = shift;
    $max >= $_ or $max = $_ for @_;
    return $max;
}

However, it would be much more efficient to pass it an array reference and use it even more efficiently List::Util::max.

+2
source

All Articles