lotsofsloths
lotsofsloths

Reputation: 121

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

I am relatively new to Perl and I do not want to use the List::Util max function to 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;
   }

Upvotes: 5

Views: 3359

Answers (3)

Sinan Ünür
Sinan Ünür

Reputation: 118148

You can write the 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 far more efficient to pass it a reference to the array and even more efficient to use List::Util::max.

Upvotes: 2

brian d foy
brian d foy

Reputation: 132858

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

One of the ways to solve problems like this is to debug your data structures. At each step you print the data you have to see if what you expect is actually in there. That can be as simple as:

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

Or for complex data structures:

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

In this case, you would have seen that @array has only one element, so there it must be the maximum.

If you want to see how list assignment and subroutine arguments work, check out Learning Perl.

Upvotes: 2

rjh
rjh

Reputation: 50304

Replace

my @array = shift;

with

my @array = @_;

@_ is the array containing all function arguments. shift only grabs the first function argument and removes it from @_. Change that code and it should work correctly!

Upvotes: 9

Related Questions