问题是:Perl 脚本计算每个数字在给定输入中出现的次数。打印每个数字的总数和所有总数的总和。
脚本是:
#!/usr/bin/perl
my $str = '654768687698579870333';
if ($str =~ /(.*)[^a]+/) {
my $substr = $1;
my %counts;
$counts{$_}++ for $substr =~ /./g;
print "The count each digit appears is: \n";
print "'$_' - $counts{$_}\n" foreach sort keys %counts;
my $sum = 0;
$sum += $counts{$_} foreach keys %counts;
print "The sum of all the totals is $sum\n";
}
我得到的输出是:
The count each digit appears is:
'0' - 1
'3' - 2
'4' - 1
'5' - 2
'6' - 4
'7' - 4
'8' - 4
'9' - 2
The sum of all the totals is 20
但我应该得到的输出是:
The count each digit appears is:
'0' - 1
'3' - 3
'4' - 1
'5' - 2
'6' - 4
'7' - 4
'8' - 4
'9' - 2
The sum of all the totals is 21
我哪里错了?请帮忙。提前致谢