2012-10-18 11 views
0

現在的問題是: 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 

我要去哪裏錯誤?請幫忙。在此先感謝

回答

1

而不是檢查整個字符串($str),檢查所有字符,但它的最後一個字符($substr)。

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

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

應該

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

固定我的答案。 (不要使用答案來提供更多信息,請使用評論和/或編輯你的帖子,一定要通過在他們的節點上發表評論讓其知道更新。) – ikegami

+0

你應該總是使用'use strict;使用警告;' – ikegami

+0

非常感謝你 – user1613245

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 
+0

非常感謝你爵士 – user1613245

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 
    }; 
+0

非常感謝你 – user1613245