perl取數組中最值


my @a=(11,22,33,44);

my $minCnt = &min(@a);

sub max       # 采用遍歷算法。先將參數中的第一個值賦給$currentMaxCnt。 # @_ 是默認的包含本函數所有參數 [如(11,22,33)]的數組。
        # shift @_ 有兩個結果: 1. 將數組 @_ 中的第一個值做為返回值(賦給了$currentMaxCnt). 2. 將@_數組第一個值彈出[此后@_的值變為(22,33)]. my $currentMaxCnt = shift @_; # 函數中使用shift時,@_可以省略。上面代碼也可以寫成這樣。 # my $currentMaxCnt = shift;

# 遍歷整個@_數組。

foreach ( @_ )

{     # $_ 表示數組@_中當前被遍歷到的元素.

if ( $_ > $currentMaxCnt )

{     # 如果發現當前數組元素比$currentMaxCnt大,那就將$currentMaxCnt重新賦值為當前元素。

$currentMaxCnt = $_;

} }     # 函數返回值為標量      $currentMaxCnt.

return $currentMaxCnt;
} print $maxCnt

 
輸出最小值:
my @a=(11,22,33,44);
my $minCnt = &min(@a);
sub min { my $currentMinCnt = shift @_;
foreach ( @_ )
{ if ( $_ < $currentMinCnt )
  {
  $currentMinCnt = $_;
  }
}
return $currentMinCnt;
}
print $minCnt
 
 
或是:
use List::Util qw(first max maxstr min minstr reduce shuffle sum);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM