Perl中数字的数字出现

时间:2012-10-18 06:09:31

标签: perl

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

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

3 个答案:

答案 0 :(得分:1)

检查整个字符串($str),而不是检查整个字符串的所有字符($substr)。

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

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

应该是

my %counts;
++$counts{$_} for $str =~ /[0-9]/g;

答案 1 :(得分:1)

#! /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
    };

答案 2 :(得分: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