当前位置:编程学习 > 网站相关 >>

perl 求和

 

CU上一道题,利用perl求和

请问如何求和?

1.    a 2

2.    a 3

3.    a 4

4.    b 4

5.    b 5

6.    c 6

7.    d 4

8.    d 1

相同的字母求和。

直接上代码哦,

1.    #!/bin/env perl

2.   

3.    use strict "subs";

4.    use List::Util qw/sum/;

5.   

6.    my %hash = ();

7.   

8.    open my $file,'<','a.txt' or die "$!\n";

9.   

10.   while (<$file>) {

11.          chomp;

12.          my @array = split;

13.          $hash{$array[0]} = [] unless exists $hash{$array[0]};

14.          push @{$hash{$array[0]}},$array[1];

15.   }

16.  

17.   close $file;

18.  

19.   for my $str (sort keys %hash) {

20.       my @tmp_array = @{$hash{$str}};

21.       printf "%-3s",$str;

22.       printf sum @tmp_array;

23.       printf "\n";

24.   }

output:

1.    [root@rhel172_16_3_248 henry]# perl a.pl

2.    a  9

3.    b  9

4.    c  6

5.    d  5

 

本文出自 “BSDerの-专注于开源领域” 博客

补充:Web开发 , 其他 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,