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,如需轉載請自行聯系原作者