Let's find the maximum value
I will explain how to find the maximum value using a Perl program.
Let's find the maximum value of the
array.
Consider an array that contains only positive numbers (> 0), such as:
@array = (1, 8, 3, 5, 7);
Sample program to find the maximum value of an array
Actually find the maximum value from the array. The List::Util module has a max function, which is not used in this example.
You can find the maximum value by preparing a variable to store the maximum value and comparing it with the elements of the array one by one.
use strict; use warnings; my @array = (1, 8, 3, 5, 7); my $max = 0; for my $num (@array) { if ($max < $num) { $max = $num; } } print "$max\n";
Execution result
8
I think that the process is very easy to understand by comparing each one.
* To simplify the code, we will handle an array that contains only positive numbers (> 0).
Let's find the maximum value of a specific column from the tabular data.
Consider the following data.
name | age |
---|---|
bob | 9 |
tom | 14 |
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 => 14}, {name =>'alice', age => 11} ];;
Sample program to find the maximum 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 => 14}, {name => 'alice',age => 11} ]; my $max = 0; for my $info (@{$array_ref}) { if ($max < $info->{'age'}) { $max = $info->{'age'}; } } print "$max\n";
Execution result
14
The process is the same as before except that the reference is dealt with.
You can copy and paste this program and try it immediately at PerlBanjo.