Perl脚本查找列中最大的数字,然后在其他列中打印出该数字和相应的值



我有一个文件,命名为file.txt文件如下....

First Last Age Years
John  M    30  2.0
Alex  K    21  3.0
Carl  G    58  4.0

我正试图写一个Perl脚本,将添加相应的行在"年龄"one_answers";Years"然后列打印与最大数字对应的名称。示例输出是"卡尔·G 62岁时"。"62";来自58和4.0的相加。我已经用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}

这可以用perl脚本完成吗?

毫无疑问,这个问题可以在Perl中解决。

下面的代码示例演示了如何实现期望的结果

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

输出
Carl G at 62 years old

参考:分裂

最新更新