I have a file, lets call it file.txt File is as follows....
First Last Age Years
John M 30 2.0
Alex K 21 3.0
Carl G 58 4.0
I am trying to write a Perl script that will add the corresponding rows in the "Age" and "Years" columns then print the name corresponding to the largest number. Example output would be "Carl G at 62 years old". The "62" comes from adding 58 and 4.0. I've done this with awk...
awk
{name=$1 OFS $2 OFS "at" OFS }
NR>1 {age = $3 $4}
age>ageMax {ageMax = age; data = name; next}
age == ageMax {data = data ageMax ORS name}
END {
print data ageMax}
Can this be done with a perl script?
CodePudding user response:
No doubt that this problem can be solved in Perl.
Following code sample demonstrates how desired result can be achieved
use strict;
use warnings;
use feature 'say';
my @header = split(' ', <DATA>);
my $max_age = 0;
my $found;
while( <DATA> ) {
my($first,$last,$age,$years) = split;
my $sum = $age $years;
$found = "$first $last at $sum years old"
if $sum > $max_age;
$max_age = $sum;
}
say $found;
__DATA__
First Last Age Years
John M 30 2.0
Alex K 21 3.0
Carl G 58 4.0
Output
Carl G at 62 years old
Reference: split