#!/usr/bin/perl -w
use strict;
# 调用函数max,取得一组数值的最大值,并输出。 my $ maxValue = & max( 11, 22, 33) ; print "maxValue=$maxValue/n" ;
sub max { ????# 采用遍历算法。先将参数中的第一个值赋给$currentMaxValue。 ????# @_ 是默认的包含本函数 所有 参数 [如 (11,22,33)] 的数 组。 ????# shift @_ 有两个结果: 1. 将数组 @_ 中的第一个值做为返回值(赋给了$currentMaxValue). 2. 将@_数组第一个值弹出[此后@_的值变为(22,33)]. ????my $ currentMaxValue = shift @ _ ;
????# 函数中使用shift时,@_可以省略。上面代码也可以写成这样。 #? my $currentMaxValue = shift;
????# 遍历整个@_数组。 ????foreach ( @ _ ) { ????????# $_ 表示数组@_中当前被遍历到的元素. ????????if ( $ _ > $ currentMaxValue ) { ????????????# 如果发现当前数组元素比$currentMaxValue大,那就将$currentMaxValue重新赋值为当前元素。 ????????????$ currentMaxValue = $ _ ; ????????} ????}
????# 函数返回值为标量$currentMaxValue. ????return $ currentMaxValue ; } |