Let's find the average value

I will explain how to calculate the average value using a Perl program.

Let's find the average value of the

array.

Consider the following array.

my @array = (8, 1, 4, 5, 7);

Sample program to find the average value of an array

Actually calculate the average value from the array. The Statistics::Lite module has a mean function, but we won't use it in this example.

The List::Util module introduced so far does not have a function to calculate the average value.

The average value can be calculated by adding the values ​​of all the data and dividing by the number of data.

use strict;
use warnings;

my @array = (8, 1, 4, 5, 7);
my $array_cnt = @array; # We are looking for the number of data.

my $sum = 0;
my $avg = 0;

for my $num (@array) {
    $sum + = $num;
}
$avg = $sum / $array_cnt;

print "$avg\n";

Execution result

Five

All the data are added one by one, and finally divided by the number of data.

If the data for which the average value is to be calculated is an array, the number of data (number of elements) can be obtained by using "@array name".

Let's find the average value of a specific column from the tabular data.

Consider the following data.

name age
bob 9
tom 13
alice 11

It is as follows when expressed by the reference of the array and the hash.

$array_ref = [
  {name =>'bob', age => 9},
  {name =>'tom', age => 13},
  {name =>'alice', age => 11}
];;

Sample program to calculate the average value of the age column

Data access has become a little more difficult due to the complexity of the referenced data,

The method of checking is the same as before.

use strict;
use warnings;

my $array_ref = [
  {name => 'bob', age => 9},
  {name => 'tom', age => 13},
  {name => 'alice',age => 11}
];

my $array_cnt = 0;
my $sum = 0;
my $avg = 0;

for my $info (@{$array_ref}) {
    $sum += $info->{'age'};
    $array_cnt += 1;
}
$avg = $sum / $array_cnt;

print "$avg\n";

Execution result

11

The process is the same as before except that the reference is dealt with.

The number of data is calculated by counting the amount of data added.

Since this is an array reference, the number of data can be dereferenced and calculated as follows.

my $array_cnt = @{$array_cnt};

You can copy and paste this program and try it immediately at PerlBanjo.

Associated Information