Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
   }
like image 493
lotsofsloths Avatar asked Feb 25 '10 01:02

lotsofsloths


People also ask

How do I get the first element of an array in Perl?

To refer to a single element of an array, the variable name must start with a $ followed by the index of the element in square brackets ( [] ). The index of the first array element is 0.

What does Unshift do in Perl?

unshift() function in Perl places the given list of elements at the beginning of an array. Thereby shifting all the values in the array by right. Multiple values can be unshift using this operation. This function returns the number of new elements in an array.

How do I get the last element of an array in Perl?

Perl provides a shorter syntax for accessing the last element of an array: negative indexing. Negative indices track the array from the end, so -1 refers to the last element, -2 the second to last element and so on.

How do I index an array in Perl?

Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets.


2 Answers

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!

like image 109
rjh Avatar answered Sep 28 '22 17:09

rjh


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.

like image 38
brian d foy Avatar answered Sep 28 '22 19:09

brian d foy