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