2013-08-18 15 views
0
#! /usr/bin/perl 
use strict; 
use warnings; 
my @array = ('0'..'9'); 
print "Enter the inp No's : "; 
while (($inp = <STDIN>) cmp "\n"){ 

} 

安格斯> perl的no.pl 輸入INP不:12123213123如何分割數字計數沒有談到在Perl次

我試圖找到多少次,每次不來以及所有位數的總和。如何分割每個數字並找到其發生的位置

回答

3

您尚未聲明$ inp。此外,您對cmp的使用很奇怪,簡單ne的工作原理相同,不會混淆任何人。

您可以通過在split使用空指令模式拆分字符串成字符,然後在哈希計算的出現次數:

#!/usr/bin/perl 
use warnings; 
use strict; 

print "Enter the inp No's : "; 
while ((my $inp = <STDIN>) ne "\n"){ 
    my %digits; 
    $digits{$_}++ for split //, $inp; 
    for (0 .. 9) { 
     print "$_ ", $digits{$_} || 0, "\n"; 
    } 
} 

的規範辦法,雖然是使用tr操作。由於它不插入,我們必須使用eval來獲取裏面的變量值:

#!/usr/bin/perl 
use warnings; 
use strict; 

print "Enter the inp No's : "; 
my %digits; 
while ((my $inp = <STDIN>) ne "\n"){ 
    for (0 .. 9) { 
     my $n = eval "\$inp =~ tr/$_//"; 
     print "$_ $n\n"; 
    } 
} 
+0

這很好用。你能解釋一下這條線是什麼嗎?「$ digits {$ _} ++ split //,$ inp;」 – Angus

+0

@Angus:'split //'返回一個字符列表。 'for'在列表中循環,'++'遞增,因此對於每個字符,與其對應的%位數值遞增。 – choroba