嗨,我是Perl的新手,在学习过程中.我有一个阵列
@array = ( 10, 40, 59, 40, 90, 100, 30, 40, 100, 20, );
Run Code Online (Sandbox Code Playgroud)
我想找到数组中的最大数字,并且还想知道数组中存在最大数字的索引.
我在做
my $maxValue = max @array;
print $maxValue; # displays the maximum number in the entire array
my ($index) = grep $array[$_] eq $maxValue , 0.. $#array;
print ($index); # this gives me the index of the maximum number which was found in the array.
Run Code Online (Sandbox Code Playgroud)
我得到的输出是100,索引为5
但实际上100在数组中会出现2次:一次在索引6处,再次在索引8.我的代码只提供了它找到的第一个索引,其中包含最大值.
如何获得具有最大值的所有索引?
my @index = grep $array[$_] eq $maxValue , 0.. $#array;
print @index;
Run Code Online (Sandbox Code Playgroud)
似乎是最简单的方法.
虽然对于数字,你真的应该使用==,即使例如100也是一个有效的字符串.