天天看点

perl 求和

CU上一道题,利用perl求和

请问如何求和?

a 2 

a 3 

a 4 

b 4 

b 5 

c 6 

d 4 

d 1 

相同的字母求和。

直接上代码哦,

#!/bin/env perl 

use strict "subs"; 

use List::Util qw/sum/; 

my %hash = (); 

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

while (<$file>) { 

       chomp; 

       my @array = split; 

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

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

close $file; 

for my $str (sort keys %hash) { 

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

    printf "%-3s",$str; 

    printf sum @tmp_array; 

    printf "\n"; 

output:

[root@rhel172_16_3_248 henry]# perl a.pl 

a  9 

b  9 

c  6 

d  5 

 本文转自dongfang_09859 51CTO博客,原文链接:http://blog.51cto.com/hellosa/699174,如需转载请自行联系原作者

上一篇: LDAP基础概念