Login

Join for Free!
116889 members
table of contents table of contents

Biology Articles » Bioinformatics » Introductory Workbook on Perl for Biology Students » 2. Perl Program for calculating averages using subroutine

2. Perl Program for calculating averages using subroutine
- Introductory Workbook on Perl for Biology Students

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.

 

 

  1. #calculate averages using subroutine
  2. $a=12;
  3. $b=13;
  4. $c=14;
  5. $d=15;
  6. $e=16;
  7. $f=17;

 

  1. $avg1 = avg($a,$b);
  2. $avg2 = avg($b,$c);
  3. $avg3 = avg($c,$d);

 

  1. sub avg{

 

  1. ($x,$y)=@_;
  2. $res=($x+$y)/2;
  3. return $res;
  4. }
  5. print "$avg1\n$avg2\n$avg3\n";
  6. exit;

 

RESULTS:

 

12.5

13.5

14.5


rating: 3.71 from 112 votes | updated on: 30 Jan 2009 | views: 92417 |

Rate article:







excellent!bad…