【发布时间】:2018-04-24 11:42:40
【问题描述】:
我正在尝试在文本文件中查找两个字符串并将它们及其频率打印出来。
#!/usr/bin/perl
#digram finder
use strict; use warnings;
#finds digrams in a file and prints them and their frequencies out
die "Must input file\n" if (@ARGV != 1);
my ($file) = @ARGV;
my %wordcount;
open (my $in, "<$file") or die "Can't open $file\n";
while (my $words = <$in>){
chomp $words;
my $length = length($words);
for (my $i = 0; $i<$length; $i++){
my $duo = substr($words, $i; 2);
if (not exists $wordcount{$duo}){
$wordcount{$duo} = 1;
}
else {
$wordcount{$duo}++;
}
}
}
foreach my $word (sort {$wordcount{$b} cmp $wordcount{$a}} keys %wordcount){
print "$word\t$wordcount{$duo}\n";
}
close($in);
- 首先我将文本文件设置为字符串 $words。
- 然后,我运行一个 for 循环并在 $words 的每个位置创建一个子字符串 $duo
- 如果哈希 %wordcount 中不存在 $duo,则程序会创建密钥 $duo
- 如果 $duo 确实存在,则该键的计数增加 1
- 然后程序按频率递减的顺序打印出图表及其频率
当我尝试运行代码时,我收到错误消息,我忘记在第 17 行声明 $word,但我什至没有字符串 $word。我不确定此错误消息来自何处。有人可以帮我找出错误的来源吗?
谢谢
【问题讨论】:
-
如果这是字面意思你的代码,那么有一个错字:
substr($words, $i; 2);——它应该有一个,而不是;。所以substr($words, $i, 2);。但这应该会给你一个syntax error之类的。 -
会不会是你实际上有
$word而不是$words,只是一个错字?