Perl realizes high watermark algorithm (method to solve multi-value comparison problem)

"High waterline" algorithm: After the flood, when the last wave recedes, the high waterline will mark the highest water level ever seen.
Let's look at the application of the "high water mark" algorithm in Perl.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

#! /usr/bin/perl;

use utf8;

  

sub max {

  my($max_so_far) = shift @_; #数组中第一个值,暂时当成最大值。

  foreach(@_){         #遍历数组@_

  if($_>$max_so_far){     #看其它元素是否有比$max_so_far大的值。

  $max_so_far = $_;}     #如果有话,更新最大值变量

  }

  $max_so_far;

}

  

my $_MaxData = &max(2,3,8,5,10);

print $_MaxData;

The first line performs a shift operation on the array @_, puts an element 2 into the maximum value $max_so_far variable, and the remaining elements in @_ are (3,8,5,10), and then uses the foreach loop to traverse the array, the new The first element 3 in the array is greater than 2, and it is moved to the $max_so_far variable, and so on, and the last 10 is the largest element in the array.

Guess you like

Origin blog.csdn.net/jh035512/article/details/128141774