开发者

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;
   }


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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜