2017-06-02 80 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; 
}