The question is:
Perl script that counts the number of times each digit appears in the given input. Print the total for each digit and the sum of all the totals.
The script is:
#!/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 Output I am getting is:
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
But the output I am supposed to get is:
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
Where am I going wrong? Please help. Thanks in advance
Instead of the inspecting the entire string (
$str), you inspect all but the last character of it ($substr).should be