【发布时间】:2011-07-16 02:30:59
【问题描述】:
如何在 Perl 中找到一个单词在文本块中出现的次数?
例如我的文本文件是这样的:
#! /usr/bin/perl -w
# The 'terrible' program - a poorly formatted 'oddeven'.
use constant HOWMANY => 4; $count = 0;
while ( $count < HOWMANY ) {
$count++;
if ( $count == 1 ) {
print "odd\n";
} elsif ( $count == 2 ) {
print "even\n";
} elsif ( $count == 3 ) {
print "odd\n";
} else { # at this point $count is four.
print "even\n";
}
}
我想找到该文本文件的“计数”字数。文件名为可怕的.pl
理想情况下,它应该使用 regex 和 最少 行代码。
编辑:这是我尝试过的:
use IO::File;
my $fh = IO::File->new('terrible.pl', 'r') or die "$!\n";
my %words;
while (<$fh>) {
for my $word ($text =~ /count/g) {
print "x";
$words{$word}++;
}
}
print $words{$word};
【问题讨论】:
-
请尽力而为,如果您仍有疑问或问题,请回到这里。这不是一个“我们会为你做功课”的网站。