题目:
一文件,内容如下
- zhangsan 80
- lisi 81.5
- wangwu 93
- zhangsan 85
- lisi 88
- wangwu 97
- zhangsan 90
- lisi 92
- wangwu 88
要求:
- 要求输出格式:(average:平均成绩,total:总成绩)
- name#######average#######total
- zhangsan xxx xxx
- lisi xxx xxx
- wangwu xxx xxx
这个题目都做烂了,原理么一样,上代码:
- #!/usr/bin/perl -w
- use strict;
- BEGIN {
- eval{ require List::Util; };
- import List::Util qw/sum/ unless $@;
- }
- my %name;
- open my $file,'<','a.txt' or die "$!\n";
- while ( <$file> ) {
- chomp;
- my @array = split /\s+/;
- $name{$array[0]} = [] unless exists $name{$array[0]};
- push @{$name{$array[0]}},$array[1];
- }
- close $file;
- print "name#######average#######total\n";
- for my $name ( sort keys %name ) {
- my @tmp_array = @{$name{$name}};
- print $name,"\t",sum(@tmp_array)/(scalar @tmp_array),"\t",sum(@tmp_array),"\n";
- }
output:
- [root@Xen ~]# perl a.pl
- name#######average#######total
- lisi 87.1666666666667 261.5
- wangwu 92.6666666666667 278
- zhangsan 85 255
本文转自dongfang_09859 51CTO博客,原文链接:http://blog.51cto.com/hellosa/593981,如需转载请自行联系原作者