1

问题是: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

我哪里错了?请帮忙。提前致谢

4

3 回答 3

2

您无需检查整个字符串 ( $str),而是检查除最后​​一个字符以外的所有字符 ( $substr)。

if ($str =~ /(.*)[^a]+/) {
    my $substr = $1;

    my %counts;
    $counts{$_}++ for $substr =~ /./g;

应该

my %counts;
++$counts{$_} for $str =~ /[0-9]/g;
于 2012-10-18T06:20:47.910 回答
2
#! /usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

my $numbers = "654768687698579870333";
$numbers =~ s{(\d)}{$1,}xmsg;

my %counts;
map {$counts{$_}++} split (/,/, $numbers);

print Dumper(\%counts);

输出

$VAR1 = {
      '6' => 4,
      '3' => 3,
      '7' => 4,
      '9' => 2,
      '8' => 4,
      '4' => 1,
      '0' => 1,
      '5' => 2
    };
于 2012-10-18T07:52:29.993 回答
0

解决方案

#!/usr/bin/perl                                             

use strict;

my $str = '654768687698579870333';
my (%counts, $sum);

while ($str =~ m/(\d)/g) {

    $counts{$1}++;
    $sum++;
}

print "The count each digit appears is: \n";
print "'$_' - $counts{$_}\n" for sort keys %counts;
print "The sum of all the totals is $sum\n";

输出

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
于 2012-10-18T06:41:11.327 回答