我有一個檔案,我們稱之為file.txt 檔案如下......
First Last Age Years
John M 30 2.0
Alex K 21 3.0
Carl G 58 4.0
我正在嘗試撰寫一個 Perl 腳本,它將在“年齡”和“年”列中添加相應的行,然后列印對應于最大數字的名稱。示例輸出將是“62 歲的卡爾 G”。“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 腳本完成嗎?
uj5u.com熱心網友回復:
毫無疑問,這個問題可以在 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
參考:拆分
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470775.html
標籤:perl
上一篇:使用sed計算反向參考
