我有一个以下格式的文本文件:
1 4730 1031782 init
4 0 6 events
2190 450 0 top
21413 5928 1 sshd
22355 1970 2009 find
我需要对第二列数据求和并将该值返回给用户。
我当前的尝试是从文本文件中读取数据,如下所示:
sub read_file{
my $data_failed = 1;
my $file = 'task_file';
if (-z $file){print "No tasks found\n";}
if(open (INFILE, "task_file" || die "$!\n")){
my @COLUMNS = qw( memory cpu program );
my %sort_strings = ( program => sub { $a cmp $b } );
my (%process_details, %sort);
while (<INFILE>) {
$data_failed = 0;
my ($process_id, $memory_size, $cpu_time, $program_name) = split;
$process_details{$process_id} = { memory => $memory_size,
cpu => $cpu_time,
program => $program_name };
undef $sort{memory}{$memory_size}{$process_id};
undef $sort{cpu}{$cpu_time}{$process_id};
undef $sort{program}{$program_name}{$process_id};
}
for my $column ($COLUMNS[2]) {
my $cmp = $sort_strings{$column} || sub { $a <=> $b };
for my $value (sort $cmp keys %{ $sort{$column} }
) {
my @pids = keys %{ $sort{$column}{$value} };
say join ' ', $_, @{ $process_details{$_} }{@COLUMNS}
for @pids;
}
}
if($total_memory_size == 1){
sum_memory_size();
}
} else { print "No tasks found"}
}
我试图求和:
sub sum_memory_size{
my @do_sum = qw(memory_size);
my $column;
my $value;
for $column (keys %{ $sort{$column}{$value} }) {
my $found;
my $sum = 0;
for $value (@do_sum) {
next unless exists $sort{$column}{$value};
$sum += $hash{$column}{$value};
delete $hash{$column}{$value};
$found = 1;
}
$sort{$column}{somename} = $sum if $found;
}
print $sum;
}
答案 0 :(得分:1)
该问题描述了一个简单的任务,似乎是一个较大问题的一部分。一个简单任务的答案是:
perl -ne '@fields=split; $sum+=$fields[1]; END { print "$sum\n" }' foo.txt
对于每一行(-ne
),将其拆分并将第二个值($fields[1]
)添加到正在运行的$sum
中。然后,在处理完所有行(END
)之后,打印总和。我从程序中获得了13078
,这也是我从上面的输入中的计算器获得的内容:)(4730 + 0 + 450 + 5928 + 1970
)。
答案 1 :(得分:1)
使用List::Util格式的sum
:
use List::Util qw{ sum };
# ...
my $memory_sum = sum(map $_->{memory}, values %process_details);