2017-06-02 120 views
0
while ($word = <STDIN>) { 
    $length = length($word) -1; # Subtract 1 for included newline char 
    $wordLength[$length]++; 
} 

print "Word length \t\t Occurrences \n\n"; 

for (my $i =1; $i <= $#wordLength; $i++) { 
if (not exists $wordLength[$i]) { 
    print "$i \t\t\t 0 \n"; 
} 
    else { 
    print "$i \t\t\t $wordLength[$i] \n"; 
    } 
} 

這一個txt文件的偉大工程讀取並輸出爲這樣:的Perl:使用代替陣列哈希

Word Length Occurrence 
1   27 
2   104 
3   1039 
4   3505 
5   7181 
6   11765 
7   15898 

我試圖讓這個使用散列而不是數組的工作,但它不似乎沒有用。這是我的嘗試:

while ($word = <STDIN>) { 
    chomp($word); 
    $length = length($word); 
    $wordLength{$word} = "$length"; 
} 

foreach $word (sort keys %wordLength) { 
    print "$word, $wordLength{$word}\n"; # print key and value 
} 
+1

爲什麼'$ wordLength {$ length}'?你現在正在鍵入單詞真是太奇怪了。 – tadman

+1

如果您仍然需要每個長度的計數,那麼您只需要從原始代碼中更改括號:'$ wordLength [$ length] ++'變爲'$ wordLength {$ length} ++'。 –

+1

此外,「它似乎不工作」不是一個有效的問題描述。你的代碼實際在做什麼?這與你所期望的有什麼不同? –

回答

1

爲什麼?任何數組在這裏都很棒。

my @occurrences_by_length; 
while (my $word = <>) { 
    chomp($word); 
    my $length = length($word); 
    ++$occurrences_by_length[$length]; 
} 

print "Length Occurrences\n"; 
for my $length (1..$#occurrences_by_length) { 
    my $occurrences = $occurrences_by_length[$length] 
     or next; 

    printf "%6d %11d\n", $length, $occurrences; 
} 

散列雖然效率較低,但可以很容易地用於幾乎沒有更改。

my %occurrences_by_length; 
while (my $word = <>) { 
    chomp($word); 
    my $length = length($word); 
    ++$occurrences_by_length{$length}; 
} 

print "Length Occurrences\n"; 
for my $length (sort { $a <=> $b } keys(%occurrences_by_length)) { 
    my $occurrences = $occurrences_by_length{$length}; 
    printf "%6d %11d\n", $length, $occurrences; 
}