The
objective of the present program is to calculate
the average of any two numbers with a use of a subroutine.
As acquainted with
the previous program that for finding out averages the method followed to calculate
involved three steps. Here, this method envisages to use the formula once and provides
three different averages. The function of the formula is done by the
subroutine. So whenever we want to calculate an average, we just pass the two
values to the subroutine. The subroutine calculates the average and returns the
result. This way we use the formula only once.
Whenever there is a
need to pass values to the subroutine we pass it by specifying the name of the
subroutine and the value/s specified in brackets (as seen in line 8, 9, and
10). The subroutine collects the values by a special variable depicted as “@_”
(as see in line 12).
Here in line 8, the
values of $a and $b are passed to the subroutine. The subroutine gets the
values and stores them in $x and $y variables for manipulation purpose. The
average is then calculated using these variables and the result is stored in
the $res variable. The value of $res is returned by using the command called
“return”. The returned value is then stored in $avg1. The same is with $avg2
and $avg3.
- #calculate averages using subroutine
- $a=12;
- $b=13;
- $c=14;
- $d=15;
- $e=16;
- $f=17;
- $avg1 = avg($a,$b);
- $avg2 = avg($b,$c);
- $avg3 = avg($c,$d);
- sub avg{
- ($x,$y)=@_;
- $res=($x+$y)/2;
- return $res;
- }
- print "$avg1\n$avg2\n$avg3\n";
- exit;
RESULTS:
12.5
13.5
14.5